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?