www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Struct lifetime wrt function return?

reply "rsw0x" <anonymous anonymous.com> writes:
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 03 2015
parent ketmar <ketmar ketmar.no-ip.org> writes:
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=20 copying/moving. compiler is free to do what it sees better. moreover,=20 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=20 copying in mind. remember that structure is value type, it can be freely=20 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=20 in DMD, and recent GDC got it too. don't know about LDC, though, but you=20 can expect that NRVO is guaranteed, yes. if new compiler will appear (SDC, for example), i think that it will do=20 NRVO too (sooner or later).=
May 03 2015