I was watching a video Curiously Recurring C++ Bugs at Facebook at 14:58 at the code (see in the example I give here) he says that is is hopelessly broken. The reason is that returning reference to a temporary object should not work.
so why it works?
#include <iostream>
#include <map>
using namespace std;
const string& get_default(
const map<string,string>& map,
const string& key,
const string& dflt) {
auto pos = map.find(key);
return (pos != map.end() ?
pos->second : dflt);
}
int main()
{
map<string,string> m;
auto& value = get_default(m,"whatever","this is the default value");
cout << value << endl;
return 0;
}
I understand why I cannot return reference to a local variable (and that fails nicely when I try to print it), but I cannot make this code fail, and I dont know why. I checked google and found that if temporary object is assigned to a reference the temporary objects lifetime will be extended (thats why it is working?). If so why is this code so hopelessy broken?
Using: gcc 7.3.0, c++14
using the comments now I can see how to make it fail: Thanks everyone :)
int main()
{
map<string,string> m;
auto& value = get_default(m,"whatever","this is the default value"); // const string& value = fails the same way
string a = "some long string";
cout << value << endl;//"some long string" will be printed here (this is how it fails - and shows that it is a mess)
return 0;
}