Géry Ogam
Géry Ogam

Reputation: 8107

What is the lifetime of a temporary object bound to a reference in a new-initializer?

From [class.temporary] of the Working Draft, Standard for Programming Language C++:

(6.12) — A temporary bound to a reference in a new-initializer ([expr.new]) persists until the completion of the full-expression containing the new-initializer.

[Note 7: This might introduce a dangling reference. — end note]

[Example 5:

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]

Does it mean that the temporary object {2,3} bound to the reference member mp of S persists until the evaluation of the expression new S { 1, {2,3} }, or until the evaluation of the expression S* p = new S{ 1, {2,3} }?

Upvotes: 4

Views: 143

Answers (1)

Jarod42
Jarod42

Reputation: 218323

Full-expression is S* p = new S{ 1, {2,3} }.

Upvotes: 1

Related Questions