0

Consider the code:

const Resource& r = ResourceContainer("foo").myResource;

What does the standard say about the lifetime of myResource?

Similar, but not sure if this is equivalent: now imagine that it was being implicitly converted via operator const Resource&(). Does that make a difference?

const Resource& r = ResourceContainer("foo");

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
  • Note: if this question has been asked before, send me the link and I will gladly delete this duplicate question. Otherwise if it's really the first time such was asked, after so many years, then Wow! doesn't deserve a down vote IMO – Patrick Parker Feb 23 '19 at 18:41

1 Answers1

1

https://en.cppreference.com/w/cpp/language/reference_initialization#Lifetime_of_a_temporary says:

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:

"Subobject thereof" looks like your case.

bipll
  • 11,747
  • 1
  • 18
  • 32
  • Thanks bipll. I once a situation where this crashed on gcc, though not on MSVC. Although there was an added wrinkle in that it was being implicitly converted via `operator Resource&()`. Does that make a difference? – Patrick Parker Feb 23 '19 at 18:32
  • it is interesting to see that they explicitly excluded user defined conversion in the section on static_cast  here: http://eel.is/c++draft/class.temporary#6 – Patrick Parker Feb 23 '19 at 21:11