Is it possible to avoid call to destructor for structs?
Adrian Matoga
dlang.spam at matoga.info
Mon Sep 25 08:39:26 UTC 2017
On Sunday, 24 September 2017 at 19:52:52 UTC, bitwise wrote:
> 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;
> }
> }
You shouldn't store the pointer to barBuffer inside Foo. The
language allows moving the structure around with a simple memcpy,
so _bar is likely to point into garbage soon after it's assigned.
Why don't you just return *cast(Bar*)barBuffer.ptr in bar()? You
could still emplace a Bar inside barBuffer in Foo's constructor,
if needed.
More information about the Digitalmars-d-learn
mailing list