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);
}
---