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?

Answers


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.


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.

  • [...]


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


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.


Need Your Help

Upload file using PUT verb in ASP.Net Web Api 2

c# http file-upload asp.net-web-api asp.net-web-api2

I would like to expose an ASP.Net Web Api 2 action using the HTTP PUT verb to upload files. This is coherent with our REST model as the API represents a remote file system (similar to WebDAV, but r...