Given the following code, where x
is a dangling const reference
to a vanished object, and is therefore undefined behavior.
auto get_vec() { return std::vector<int>{1,2,3,4,5}; }
const auto& x = get_vec().back();
It seems like neither GCC 7.3, Clang 6.0 and MSVC is able to emit a warning, even with all warnings enabled.
Does anyone know if it is any way to emit a warning in these cases?
Is there any difference between const auto&
and auto&&
in these cases?
Note, if back()
would return by value, it wouldn't be undefined behavior as the lifetime temporary object x is extended to function scoop.
Long story: I have a code base where const auto&
is used as the default way of initializing variables, and for some odd reason these cases executes correctly using MSVC, but when compiled with Clang for android, every occurance results in a wrongly assigned value. For now the solution seems to investigate every const auto&
in the whole code base.
Also, in many cases the const auto&
refers to a heavy object returned by reference so simply removing the &
is not a solution.
One more thing, I'm responsible for the miss use of const auto&
:)