Assuming I have:
- class A which is non-copyable
- class B which has as a member, const A& a (and takes an A in its constructer and sets it in its initialization list)
- a function
A GenerateA();
Does this mean that it should be valid to do:
B(GenerateA())
?
i.e, does the const ref mean that no copy of the A that generateA() returns is done? And does that mean that the scope of the returned temporary is extended for as long as B exists?
EDIT: Addon question from the comments:
Is it acceptable to return a A& from GenerateA() to a local A, if the lvalue is a const A&?
Thanks!
As it has already been stated by others,
A GenerateA()cannot compile ifAis not copyable.Regarding the const ref : no, the lifetime of the temporary will not be extended to the lifetime of B. The standard [12.2.5] states :
So yes, extension of the lifetime of a temporary exists in some contexts (and is sometime truly useful : see this article), but not in the one you presented.
Regarding your last question, it’s not legal to return a reference to a local variable from
GenerateA()(and binding the result to a const reference won’t be of any help).