Problem with dtor behavior

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 27 13:28:47 PDT 2017


On Thursday, 27 July 2017 at 19:19:27 UTC, SrMordred wrote:
> //D-CODE
> struct MyStruct{
>     int id;
>     this(int id){
>         writeln("ctor");
>     }
>     ~this(){
>         writeln("dtor");
>     }
> }
>
> MyStruct* obj;
> void push(T)(auto ref T value){
>     obj[0] = value;
> }
>
> void main()
> {
>     obj = cast(MyStruct*)malloc( MyStruct.sizeof );
>     push(MyStruct(1));
> }
>
> OUTPUT:
> ctor
> dtor
> dtor
>
> I didnt expected to see two dtors in D (this destroy any 
> attempt to free resources properly on the destructor).

AFAICT it's because opAssign (`obj[0] = value` is an opAssign) 
creates a temporary struct object (you can see it being destroyed 
by printing the value of `cast(void*) &this` in the destructor).

> Can someone explain why is this happening and how to achieve 
> the same behavior as c++?

Use std.conv.emplace:

---
import std.conv : emplace;

void push(T)(auto ref T value){
	emplace(obj, value);
}
---


More information about the Digitalmars-d-learn mailing list