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); }
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.
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.
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.
You cannot reassign a reference.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With