~= call copy ctor?

monarch_dodra monarchdodra at gmail.com
Fri Jul 20 08:26:34 PDT 2012


On Friday, 20 July 2012 at 13:50:20 UTC, Namespace wrote:
> New question:
>
> I have this code:
> [code]
> import std.stdio;
>
> struct Test {
> public:
> 	this(int i = 0) {
> 		writeln("CTOR");
> 	}

Be careful about "int i = O". Structs are not allowed to have 
default constructors. This is so they can have a static default 
value of Test.init which can be efficiently mem-copied.

> 	this(this) {
> 		writeln("COPY CTOR");
> 	}
>
> 	~this() {
> 		writeln("DTOR");
> 	}
> }
>
> void main() {
> 	Test[] _arr;
>
> 	_arr ~= Test(0);
>
> 	writeln("end main");
> }
> [/code]
>
> And as output i see:
>
> CTOR
> COPY CTOR
> DTOR
> end main
>
> Why on earth....?
>
> I create a struct Test. It's not a local variable, it's 
> directly assigned, but it is copied and the original is 
> destroyed. Why?

Seems perfectly reasonable to me.

~= is an operator, eg, a function that needs arguments. Test(0) 
_IS_ a local variable that you pass as an argument in main 
(CTOR), and you pass it to the operator. From there, 
operator!"~=" will build a new object straight from the old 
object (COPY CTOR). Then, you return to main, and the stack local 
Test(T) object is destroyed (DTOR). Finally, main ends (end main).

The last missing destructor is the one of the object in the array.

> If i store something important, like a pointer, in Test and 
> will free him in the DTOR i cannot assign this way Test's to an 
> array, because the pointer was deleted because the DTOr was 
> called.

Well if you do that, then your object can't be copied ever.
--------

Here is a funner test though:
Though:
Test TestBuilder(int i)
{
   return Test(i);
}
void main() {
   Test[] _arr;
   _arr ~= TestBuilder(3);
   writeln("end main");
}

Output:
   CTOR
   COPY CTOR
   end main

_This_ smells funky to me. There should be a destroyer somewhere 
in there: At the end of the day, there is only 1 element left in 
memory, but two have been created, yet none have been destroyed !?


More information about the Digitalmars-d-learn mailing list