opAssign in D2

Koroskin Denis 2korden at gmail.com
Mon Jun 2 11:29:31 PDT 2008


On Mon, 02 Jun 2008 20:08:29 +0400, lurker <lurker at lurker.com> wrote:

> hi,
>
> i like to copy objects such as:
>
> class A {....}
>
> A xxx; // some things are done ...
>
> A yyy = xxx;
>
> how can one do that in D2 easy? are any samples?
>
> thanks
>
>

You shouldn't use this for by design, it's not supported for reference  
types, only for structs.
But you might consider wrapping the class into a struct with overloaded  
opAssign semantics.
It sould work fine for you (after opImplicitCast is implemented :)).

The other limitation of opAssign is that you can't override opAssign to  
accept object of the same type:

T t1;
T t2;
t1 = t2; // can't be hooked :(

Compiler just makes a plain bitwise copy of the object in any case.

I was trying to implement C++-style reference (Ref!(T) template), it works  
fine but the I didn't find any way to disallow reference rebindment:

int i = 5;
Ref!(int) ri = i;

ri = 0;
assert(ri == i);

--ri;
assert(ri == i);

ri *= 2;
assert(ri == i);

ri ^= 4;
assert(ri == i);

int t = 0;

ri = Ref!(int)(&t);	// that's what I want to disallow, but can't :(
assert(ri == i);

Anyone knows how to workaround this?


More information about the Digitalmars-d-learn mailing list