Reputation: 3867
Suppose you have this code (in c++14) :
auto && a = a_function_returning_a_temp_rvalue();
Where is stored the returned value, when is its destructor called, is a
const
(considering the function doesn't return a const
), how is it specified in the standard ?
(is it even legal)
Also, do you confirm, the temporary is really bound to a
, and no operator=
neither constructors will be called ?
It compiles on g++ and avoid typing long template classes, but before using it, I would like to check if it's clearly stated in c++14
Upvotes: 0
Views: 91
Reputation: 302767
The rule is in [class.temporary]:
There are three contexts in which temporaries are destroyed at a different point than the end of the full-expression. [...] The third context is when a reference is bound to a temporary.116 The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
— A temporary object bound to a reference parameter in a function call (5.2.2) [...]
— The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is [...]
— A temporary bound to a reference in a new-initializer (5.3.4) persists until [...]
In this example:
auto && a = a_function_returning_a_temp_rvalue();
I'm assuming the function returns something of type T
(as opposed to T&
or T&&
). In this case, we do have a temporary bound to a reference, and none of those exceptions apply. Hence, the lifetime of that temporary is extended for the lifetime of a
.
Upvotes: 2
Reputation: 72271
Yes, this is guaranteed to work.
[12.2/4-5]
There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. ...
The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing the call.
The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
A temporary bound to a reference in a new-initializer persists until the completion of the full-expression containing the new-initializer.
No constructor or operator=
is called to initialize a
, and a
is not const
if it doesn't need to be.
Upvotes: 1