Is it possible to avoid call to destructor for structs?

bitwise bitwise.pvt at gmail.com
Sun Sep 24 19:52:52 UTC 2017


On Sunday, 24 September 2017 at 17:11:26 UTC, Haridas wrote:
> In the following code, Bar is an element of struct Foo. Is 
> there a way to avoid a call to ~Bar when ~Foo is getting 
> executed?
>

Don't construct it to begin with.

struct Bar {
     import std.stdio : writeln;
     int a = 123;
     void boink() { writeln(a); }
     ~this(){ writeln("bar dtor"); }
}

struct Foo
{
     ubyte[Bar.sizeof] barBuffer;
     Bar* _bar = null;

     ref Bar bar()
     {
         import std.conv : emplace;

         if(!_bar) {
             _bar = cast(Bar*)barBuffer.ptr;
             emplace(_bar);
         }

         return *_bar;
     }
}

int main(string[] argv)
{
     Foo foo;
     foo.bar.boink();
     return 0;
}



More information about the Digitalmars-d-learn mailing list