Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "rebinding" references in C++ like this legal?

Is the following legal in C++?

As far as I can tell, Reference has a trivial destructor, so it should be legal.
But I thought references can't be rebound legally... can they?

template<class T> struct Reference {     T &r;     Reference(T &r) : r(r) { } };  int main() {     int x = 5, y = 6;     Reference<int> r(x);     new (&r) Reference<int>(y); } 
like image 651
user541686 Avatar asked Jan 13 '14 21:01

user541686


People also ask

Are references copyable?

Sure, if you read/write a value via a reference, you read/write the original. But you can certainly copy a reference without copying the original object it refers to. Unless you mean if you copy a reference, whatever you do to the copy also applies to the original reference, not the original object being referred to.

Can we reassign reference?

Remember, once you initialize a reference, you cannot reassign it. A reference practically stands for an object. You cannot make it 'point' to a different object.

Do we have references in C?

No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.

Can reference be modified?

You cannot reassign a reference.


2 Answers

You aren't rebinding a reference, you're creating a new object in the memory of another one with a placement new. Since the destructor of the old object was never run I think this would be undefined behavior.

like image 191
Mark Ransom Avatar answered Sep 22 '22 08:09

Mark Ransom


There is no reference being rebound in your example. The first reference (constructed on line two with the name r.r) is bound to the int denoted by x for the entire of its lifetime. This reference's lifetime is ended when the storage for its containing object is re-used by the placement new expression on line three. The replacement object contains a reference which is bound y for its entire lifetime which lasts until the end of its scope - the end of main.

like image 23
CB Bailey Avatar answered Sep 23 '22 08:09

CB Bailey