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…
The standard does not cover
[2]. It allows an rvalue to be bound to a const reference, but that doesn’t allow you to return a const reference and have the lifetime of the rvalue it is bound to extended as well.And true, static analysis could catch this, but as always it’s a trade-off. C++ compilation is slow enough as it is, so compiler writers have to weigh the benefits of further static analysis which might allow them to produce better diagnostics, against the increased compilation time.