It is undefined behavior the compiler is not even obligated to provide a diagnostic let alone make it an error. The draft C++ standard in section 1.4
Implementation compliance says:
The set of diagnosable rules consists of all syntactic and semantic
rules in this International Standard except for those rules containing
an explicit notation that “no diagnostic is required” or which are
described as resulting in “undefined behavior.”
This is mainly due to the fact that it is not always trivial for the compiler to determine when undefined behavior is present and forcing the compiler to detect all cases would be considered an undue burden.
Although modern compilers are pretty good at catching all sorts of bad behavior include undefined behavior, with gcc
and clang
I find the following set of flags to be helpful: -Wall -Wextra -Wconversion -pedantic
.
You can turn these into errors you can use -Werror
which I recommend strongly. It forces you to understand why each warning is being generated and have the discipline to find better solutions which will save you a lot of pain in the long run.
Note, the one case where we can probably force an error for detectable undefined behavior is when we are assigning the result of a constexpr function to a constexpr variable since constant expression exclude undefined behavior.
So the following C++14 code:
constexpr int& getValue()
{
int i = 10;
return i;
}
int main()
{
constexpr int &p = getValue();
//...
}
generates the following error using clang
:
error: constexpr variable 'p' must be initialized by a constant expression
constexpr int &p = getValue();
^ ~~~~~~~~~~