I've just been bitten by a nasty undefined behavior due the returning a reference to a local variable.
We know it's evil, and generally the compiler prints a nice warning
to tell us so... well gcc (3.4.2) does not seem to push the checks too far though.
std::string get_env_value(std::string const& key);
std::string const& get_phase()
{
std::string const& phase = get_env_value("PHASE"); // [1]
std::cout << "get_phase - " << phase << '\n';
return phase; // [2]
}
This compiles without a glitch, and yet we fall in the nasty realm of undefined behavior.
Line [1]
is okay because the standard specifies that the lifetime of a variable bound to a const reference should be extended to match the lifetime of the const reference.
Line [2]
seems okay too...
- Do the C++ specifications cover this case ?
- Does anyone know if this is usually diagnosed ? (I may miss a flag or something...)
It seems to me that static analysis should be able to tell that having use a "lifetime extension" for [1]
, [2]
is not safe, but it could get ugly rapidly I guess...