unagi
unagi

Reputation: 466

Lifetime of const reference variable not extended

Binding a temporary to a const reference extends its lifetime; cf. GotW #88.

Why does not this work on this snippet? Live here.

#include <iostream>
#include <string>

struct A {
    A() : s("abc") {}
    const std::string& s;
};

struct B {
    const std::string& s = "def";
};

int main() {
    A a;
    std::cout << a.s << std::endl;
    B b;
    std::cout << b.s << std::endl;
}

Bonus question: How to trigger a warning with gcc?

Upvotes: 1

Views: 489

Answers (4)

D&#225;niel S&#225;ndor
D&#225;niel S&#225;ndor

Reputation: 1294

cppreference.com says:

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.

http://en.cppreference.com/w/cpp/language/reference_initialization

Upvotes: 1

M.M
M.M

Reputation: 141554

From C++14 [class.temporary]/5:

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 member in a constructor’s ctor-initializer persists until the constructor exits.

  • [...]

Upvotes: 3

R Sahu
R Sahu

Reputation: 206577

In the article that you linked to, you will find:

(Note this only applies to stack-based references. It doesn’t work for references that are members of objects.)

That's why the references in a and b are not valid. They don't extend the life of the temporaries.

Upvotes: 3

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

The lifetime is only extended to the end of the compiler generator constructor for B. When the constructor returns, the temporary string created to hold "def" will be destroyed leaving you with a dangling reference.

Upvotes: 0

Related Questions