Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of code which incorrectly tries to re-seat a reference

Tags:

c++

reference

As per my understanding, C++ does not allow you to re-seat a reference. In other words, you cannot change the object that a reference "refers" to. It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();

Immediately my alarm bells went off on the last line of code above. Wasn't the code trying to re-seat a reference? Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object. The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

like image 339
LeopardSkinPillBoxHat Avatar asked Nov 29 '25 08:11

LeopardSkinPillBoxHat


1 Answers

You can't "reseat" a reference, because it's syntactically impossible. The reference variable you use which refers to the object uses the same semantics as if it was an object (non-reference) variable.

like image 125
Charles Salvia Avatar answered Nov 30 '25 21:11

Charles Salvia