Referencing the same variable that you're declaring

196 views Asked by At

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?

2

There are 2 answers

13
Bo Persson On BEST ANSWER

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 if int 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?

4
Daniel On

There is no error or warning because its equivalent to:

QString str;
str = str.toUpper();

Just like

QString str = "aaa";

is same as

QString str;
str = "aaa";

To do this in the same statement you need to use constructor, which won't compile:

QString str(str.toUpper());

just like:

QString str("aaa");

is not equivalent to

QString str;
str = "aaa";