user695652 user695652 - 1 year ago 68
C++ Question

Reference to return value of function

I am confused whether in the following snippet

is guaranteed to be valid, i.e., whether I am allowed to store function return values as const references?

I am asking because the return value is stored on a stack-frame, which might be invalid soon after the value was returned.

Foo getFoo() {
return Foo();

void bar() {
const auto& foo = getFoo();

// more function calls...

// is foo guaranteed to be valid?

Answer Source

It is valid C++, however be aware that some compilers (e.g. Visual Studio 2015, as far as I know) do not implement it properly.

According to the standard (N4140):

12.2 Temporary objects

4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.

5 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:

(some exceptions)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download