Is it possible to reset reference to another value in C++?

  • A+
Category:Languages

I know generally it's impossible to reset a reference after it's already initialized.

However, I somehow try out the following code and it happens to work on both clang++ and g++.

My question is, is the following a valid (behavior-defined) C++?

std::string x = "x"; std::string y = "y"; std::string i = "i"; std::string j = "j";  // now references to x, y std::pair<std::string &, std::string &> p { x, y }; p.first = "1"; //changes x p.second = "2"; //changes y // now references to i, j new (&p) std::pair<std::string &, std::string &> {i, j}; p.first = "1"; //changes i p.second = "2"; //changes j 

The above code works on g++ and clang++, but is it good C++? Thanks.


My question is, is the following a valid (behavior-defined) C++?

It could be. The key here is that pair. You ended the lifetime of the pair object, and started the lifetime of another pair object in the same storage (the placement new does both of these things).

But you should be aware you aren't rebinding any references. You kill an object that held references, and create a new on in the same spot. Conceptually, you had two "old" references, and now two "new" ones.

Your code could be fine because the pair is a simple structure that holds a pair of references, and it would be valid if the pair held any trivially destructible types. If however the d'tor of any pair element is not trivial, you'll have undefined behavior. Because destructors will not be executed as part of placement new.

The problem as Passer By noted, is that you can't use p to refer to the "new object", because it holds references. That would be the cause of UB.

is it good C++?

That's debatable. It certainly is not something one would expect to see often.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: