A point from N3290 C++ draft, § 12.2, 5th point, line 10.
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 temporary bound to a reference in a new-initializer (5.3.4)
persists until the completion of the full-expression containing the
new-initializer. [ Example:struct S { int mi; const std::pair<int,int>& mp; }; S a { 1, {2,3} }; S* p = new S{ 1, {2,3} };// Creates dangling reference— end example ] [ Note: This may introduce a dangling reference,
and implementations are encouraged to issue a warning in such a
case. — end note ]
This is the added point when compared to C++03. But the example is not understandable for me. Can you please explain this point with any other example?
I know what dangling references and temporary objects are and that std::pair holds two values of possibly different data types.
Temporaies in general last only to the end of the expression that they were created in:
If you create a temporary object and bind it to a reference. You extend its lifespan to the same lifespan of the reference it is bound too.
The exception to this rule is when the temporary is bound to a reference in a new initializer.
But here we are binding the new temporary object to the member
const std::pair<int,int>& mp;This is a const reference. But the temporary object it is bound to will be destroyed at the ‘;’ in the above expression so mp will be a reference to an object that no longer exists when you try and use it in subsequent expressions.