Search code examples
c++referencelifetimestring-literals

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?


Solution

  • 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.