3
votes

I'm looking up lifetime of a temporary on cppreference.com and I found something changed from C++14:

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

...

a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists. (note: such initialization is ill-formed as of DR 1696) (until C++14)

I checked the standard there's really no such statement. ($12.2/5 Temporary objects [class.temporary])

Does it mean from C++14 the lifetime of a temporary bound to a reference member will be extended to the object's lifetime?

I've tried the following code with GCC and CLANG both seem not, the temporary will be destroyed when constructor ends.

#include <iostream>

struct X {
    ~X() { std::cout << "X dtor\n"; }
};
struct Y {
    Y() : x_(X()) { std::cout << "Y ctor\n"; }
    const X& x_;
    ~Y() { std::cout << "Y dtor\n"; }
};
int main()
{
    Y y;
    std::cout << "Hello, world!\n";
}

result:

Y ctor
X dtor
Hello, world!
Y dtor

Do I misunderstand it?

1
Did you read the defect report?NathanOliver
YES (you did misunderstand it)Walter

1 Answers

6
votes

The defect report you cited has been adopted, and N4582 already includes the new wording in [class.base.init]:

A temporary expression bound to a reference member in a mem-initializer is ill-formed. [Example:

struct A {
  A() : v(42) { }  // error
  const int& v;
};

— end example ]

So it's not extended for the object's lifetime - the code is simply ill-formed. gcc and clang both emit warnings on your code on every version I've tried, which I think is conforming but ideally they should error there.