I've seen the following type mistake a couple of times while working with C++ code:
QString str = str.toUpper();
This can be a fairly easy mistake to make and yet it compiles and executes (sometimes with crashes, sometimes without). I can't see any circumstances under which it would be something that you'd actually want to do.
Some testing has revealed that the copy constructor is invoked, not the default one, and that the object is being given itself from within the copy constructor.
Can anyone explain why this isn't a compiler error, or even a warning?
Technically the object
str
is defined when you reach the equal sign, so it can be used at that point.The error is in trying to initialize the object with itself, and the compiler is allowed to warn about that (if it is able to detect it). However, as the detection is not possible in every case, the compiler is not required.
For example
int x = f(x);
is entirely correct ifint f(const int&)
doesn't use the value of its parameter. How is the compiler to know that if it hasn't seen the function body yet?