On 11/02/2012 05:29 AM, Dan wrote:
> The following works, but I want to make opAssign in D take const ref D.
> It needs to still print "(dup here)". How can this be done?
>
> Thanks
> Dan
>
> ----------------
> import std.stdio;
>
> struct A {
> char a[];
> this(this) { a = a.dup; writeln("(dup here)"); }
> }
> struct B { A a; }
> struct C { B b; }
> struct D {
> C c;
> // How can I make this take const ref D other
> ref D opAssign(ref D other) {
> c = other.c;
> return this;
> }

Try the copy-then-swap idiom, which is both exception-safe and efficient:

import std.algorithm;

// ...

    ref D opAssign(D other) {
        swap(c, other.c);
        return this;
    }

There may be corner cases where this is not efficient, but considering that assignment involves two sub-operations (make a copy of the new state and destroy the old state), the above is doing exactly that. (It is the same idiom for strongly exception-safe operator= in C++.)

That has been the observation that led me to understand that by-value is the way to go with struct opAssign. Please let us know whether it has weaknesses. :)

> }
>
> void main() {
> D d, d2;
> d2 = d;
> }
>

Ali

Reply via email to