Struct copy and destruction

Dan Olson zans.is.for.cans at yahoo.com
Sun Apr 10 09:41:32 PDT 2011


Morlan <home at valentimex.com> writes:

>>> I was curious too, so found in Section 7.1.5.1 the description of
>>> opAssign using a swap.  That explains it I think.
>
>
> Section 7.1.5.1 does not apply because it concerns the case where you
> define your own overload of the assignment operator. In my example the
> default assignment is used.  The description of the default assignment
> is somewhat vague and does not ever mention the fact that the
> destructor of the target is called as its byproduct. In fact, if you
> add opAssign to S you will see that the destructor is not called any
> more. It is probably assumed that if you define your own assignment
> its up to you to take care of such details. This whole subject needs
> some reworking in the documentation.

But if you define the more general opAssign() that takes a value for the
rhs instead of a ref, then the dtor is called (second example on page
257 with swap).

Let me explain my thinking, maybe I was inferring too much.  I noticed
that the example of opAssign with the swap takes a rhs by value, so it
will be a copy with its own lifecycle and must have the dtor called.
The compiler could generate opAssign taking rhs by value.

I think if the address of struct S to the ctor and dtor is printed
(e.g.)

  writeln(&this, ": ", name, " destructor");

it will show that the dtor is question is called on copy.  I don't think
this is a bug, just compiler implementation of assignment so it can take
non lvalues.

-- 
Dan


More information about the Digitalmars-d mailing list