1

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?

Matthew James Briggs
  • 2,085
  • 2
  • 28
  • 58
  • Neat how questions bunch up like this: http://stackoverflow.com/questions/42868517/why-can-you-intialize-a-const-reference-but-not-a-non-const-reference-from-an-rv Some useful commentary on the whys and wherefores. – user4581301 Mar 17 '17 at 23:57
  • It's important to note the difference between "temporary" and "rvalue". The latter is strictly more general. For example, compare `const int& r = 5;` and `const int& q = std::move(5);`. Both are rvalues, one is a disaster. – Kerrek SB Mar 18 '17 at 00:05

1 Answers1

2

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]

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • _"Each case is well defined."_ Well, no, it depends what `WeakPtr.lock()` and `mSomething.lock()` return. The final case is the only assuredly well-defined case. – Lightness Races in Orbit Mar 18 '17 at 00:25
  • Basically, it's well-defined _iff_ a reference to a local is not being returned. Basically. – Lightness Races in Orbit Mar 18 '17 at 00:25
  • @BoundaryImposition in which case is it not well-defined when the function returns a temporary object, an rvalue, as stated in the question? A reference (to a local, or otherwise) is an lvalue. – eerorika Mar 18 '17 at 10:08
  • No, the question does not guarantee that `WeakPtr.lock()` and `mSomething.lock()` do not return references to locals. The expression's value category is largely irrelevant; the lifetime of the chained reference is. – Lightness Races in Orbit Mar 18 '17 at 15:13