Understand lifetime extension limits for references
Binding a temporary directly to const T& extends the temporary’s lifetime. This is useful, but easy to misuse when subobjects are involved.
const Object& a = getObject(); // Lifetime extension if getObject() returns by valueconst Object& b = CreateParent().object; // Lifetime extension for Parent temporary (and therefore its member)const Object& c = CreateParent().getObject(); // WARNING: usually no lifetime extension of the referenced subobjectIn the third case, getObject() may return a reference to a subobject owned by a temporary parent. Although direct member access can keep that temporary alive (second case), this does not generally apply through a method that returns a reference. The parent is destroyed at the end of the full expression, so c may dangle.
Prefer safer designs
Section titled “Prefer safer designs”- Return by value when practical
- Avoid exposing references to subobjects of temporaries
- Keep owner lifetime explicit at call sites