May 04, 2015 Struct lifetime wrt function return? | ||||
---|---|---|---|---|
| ||||
I remember reading that guaranteed RVO was part of the D
standard, but I am completely unable to find anything on it in
the specification.
I'm also unable to find anything in it that explicitly states the
lifetime of returning a stack-local struct from a function.
However, it does state
>Destructors are called when an object goes out of scope.
So without guaranteed RVO I am quite confused.
I apologize because this code will likely be poorly formatted.
import std.stdio;
struct S{
~this(){
writeln("Goodbye!");
}
}
S foo(){
S s;
return s;
}
void main()
{
S s2 = foo();
}
This says "Goodbye!" exactly once, indicating(?) that S was
NRVO'd which means the scope of s went from foo to main.
However, is this a guarantee by the standard? Is an
implementation allowed to define foo such that it returns by copy
and calls a destructor on s, meaning "Goodbye!" would print out
twice?
|
May 04, 2015 Re: Struct lifetime wrt function return? | ||||
---|---|---|---|---|
| ||||
Posted in reply to rsw0x Attachments: | On Mon, 04 May 2015 02:29:19 +0000, rsw0x wrote:
> This says "Goodbye!" exactly once, indicating(?) that S was NRVO'd which means the scope of s went from foo to main. However, is this a guarantee by the standard? Is an implementation allowed to define foo such that it returns by copy and calls a destructor on s, meaning "Goodbye!" would print out twice?
actually, you'd better avoid code that makes assumptions about struct copying/moving. compiler is free to do what it sees better. moreover, phobos can use moving too. but it also can use copy/destroy.
what i want to say is that you should write your code with structure copying in mind. remember that structure is value type, it can be freely moved and copied.
you can also explicitly disable structure copying with
@disable this (this);
and if you concerned about code optimisation... well, NRVO is guaranteed in DMD, and recent GDC got it too. don't know about LDC, though, but you can expect that NRVO is guaranteed, yes.
if new compiler will appear (SDC, for example), i think that it will do NRVO too (sooner or later).
|
Copyright © 1999-2021 by the D Language Foundation