Search code examples
c++c++11referencelvaluervalue

What happens when assigning an rvalue to 'const auto&'


What happens in this case?

// assume WeakPtr is valid and has not expired
const auto& something = WeakPtr.lock();
something->doStuff();

Is this undefined?

Does it change in this scenario?

std::shared_ptr<Something> getSomething() { return mSomething.lock(); }
const auto& something = getSomething();

And how about this?

std::vector<int> getInts() { return std::vector<int>{ 1, 2, 3 }; }
const auto& ints = getInts();

In each of these cases const auto& implies that I want to bind a reference to the object, but in each of these cases I am binding it to a temporary rvalue object. Am I inviting disaster?


Solution

  • Is this undefined?

    Each case is well defined.

    What happens in this case?

    In each case, the lifetime of the temporary object is extended to match the lifetime of the const reference as is described in the [class.temporary] section of the standard.

    [class.temporary] (standard draft)

    4 There are two contexts in which temporaries are destroyed at a different point than the end of the full- expression. The first context is ... [irrelevant to your cases]

    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 ... [a few exceptions which do not apply to your cases]