Surprise destructor call...
Manu
turkeyman at gmail.com
Wed Aug 14 13:56:08 UTC 2024
On Wed, 14 Aug 2024 at 21:56, Dennis via Digitalmars-d <
digitalmars-d at puremagic.com> wrote:
> On Wednesday, 14 August 2024 at 09:19:55 UTC, Manu wrote:
> > Also surprisingly, if I comment out the constructor, the
> > compile error
> > about the destructor goes away. I can't see why the
> > constructor's existence
> > affects the destruction semantics in fun()?
>
> The compiler's logic goes as follows:
>
> ```D
> return Thing(null);
> ```
>
> Since `Thing` has a constructor, this gets rewritten to:
>
> ```D
> return Thing().this(null);
> ```
>
> Now we have a 'DotVarExp' with a struct literal on the left, and
> the struct has a destructor. Since internally expression
> temporaries can't have destructors, it gets extracted into a
> temporary variable:
>
> ```D
> return ((Thing __slThing3 = Thing();) , __slThing3).this(null);
> ```
>
> Then `__slThing3` goes out of scope and needs a destructor call.
>
> So clearly, in this case you don't want the temporary, but in
> other cases (`return Thing(null).field;`) you do need it, so I'm
> thinking about what the right conditions should be for the
> temporary.
>
Well, the condition is that NRVO should elide the copy/move... it should be
constructed at the caller's scope in this case.
Your example `Thing(null).field` is not the same thing, because it's not
NRVO at all.
I guess this is a bug then?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20240814/66a3c5b4/attachment.htm>
More information about the Digitalmars-d
mailing list