Having a class holding a reference I would expect the following code to fail miserable, but it compiles:
#include <iostream>
struct ReferenceHolder
{
std::string& str;
ReferenceHolder(std::string& str)
: str(str)
{}
};
// Why does this compile?
ReferenceHolder f() {
std::string str = "Hello";
return ReferenceHolder(str);
}
int main() {
ReferenceHolder h = f();
std::cout << "Should be garbage: " << h.str << '\n';
return 0;
}
Compiler: g++ 4.7.2 (with -std=c++11)
Edit: Even with -fno-elide-constructors it compiles happily