Problem with dtor behavior

SrMordred via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 27 12:19:27 PDT 2017


//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


//C++ CODE
#include <iostream>
#include <string>
using namespace std;
void writeln(string s){ cout << s << '\n'; }

struct MyStruct{
     int id;
     MyStruct(int id){
         writeln("ctor");
     }
     ~MyStruct(){
         writeln("dtor");
     }
};

MyStruct* obj;
template<class T>
void push(T&& value){
     obj[0] = value;
}


int main()
{
     obj = (MyStruct*)malloc( sizeof(MyStruct) );
     push(MyStruct(1));
     return 0;
}

OUTPUT:
ctor
dtor


I didnt expected to see two dtors in D (this destroy any attempt 
to free resources properly on the destructor).
Can someone explain why is this happening and how to achieve the 
same behavior as c++?
Thanks :)


More information about the Digitalmars-d-learn mailing list