digitalmars.D.learn - opAssign in D2
- lurker (7/7) Jun 02 2008 hi,
- BCS (9/23) Jun 02 2008 first, classes are reference types so the above needs to be:
- Koroskin Denis (28/35) Jun 02 2008 You shouldn't use this for by design, it's not supported for reference
- BCS (3/28) Jun 02 2008 It's not really clean but making a dup() method would be constant with D...
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
Jun 02 2008
Reply to lurker,
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
first, classes are reference types so the above needs to be:
A xxx = new A;
// some things are done ...
A yyy = xxx;
second, that assignment will work as is but will act as a reference copy
(you get two copies of the reference to the same object). If you want a real
copy you can use structs or generate a deep copy function for the class.
I don't use 2.0 so someone else will need to fill in the details.
Jun 02 2008
On Mon, 02 Jun 2008 20:08:29 +0400, lurker <lurker 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?
Jun 02 2008
Reply to Koroskin,On Mon, 02 Jun 2008 20:08:29 +0400, lurker <lurker lurker.com> wrote:It's not really clean but making a dup() method would be constant with D's arrays.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? thanksYou 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:
Jun 02 2008









BCS <ao pathlink.com> 