Copying reference types by value

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Wed Apr 17 09:17:28 PDT 2013


Hello all,

Suppose I have a couple of variables a, b that are reference types (e.g. arrays
or classes).  Then, setting a = b will mean that the two reference the same entity.

If they're arrays, one can copy the values readily by setting a[] = b[], but
this isn't a generic solution -- suppose instead of arrays, I a and b are
instances of

	class A {
		int one;
		double two;
		size_t three;

		this(int _one, double _two, size_t _three)
		{
			one = _one;
			two = _two;
			three = _three;
		}
	}

Now, I can see several solutions.  The first is just to define a generic copy
function, like,

	void copyMyClass(const A from, ref A to) { ... }

... which copies over values.  However, as a general solution that seems a bit
dodgy as it presumes I have the right to read and write all internal values of
the class.

Defining a .dup method doesn't seem appropriate either because although it
allows me to duplicate the values, setting

	a = b.dup;

will mean that a now becomes a new object, and any other entities that were
pointing at the original a will suddenly become decoupled from its values.  So,
if I do,

	c = a;
	a = b.dup;

... I will no longer have c equal to a.

So, can anyone recommend an appropriate general method for copying the values of
one reference type instance to another?  Perhaps an appropriate operator to
overload?

Thanks & best wishes,

    -- Joe


More information about the Digitalmars-d-learn mailing list