If I use a const reference to another member, is it possible that this reference gets invalidated?
class Class {
public:
const int &x{y};
private:
int y;
};
For example when I use instances of this class in a vector
which increases its capacity after a push_back
.
According to the standard all iterators and references are invalidated if
a vector has to increase its capacity. Is the reference still valid after that?
Assuming this is a reference to another member from the same instance, you need to override copy constructor to initialize it. Default copy constructor will copy the reference to 'y' from the old instance which might be invalidated.
Why do you need a reference to a member is another question.
P.S. also you need to override an assignment operator for the same reason.
This is currently not safe, as when you copy an instance of
Class
,x
will reference they
of the copied object, not its owny
. You can see this by running the following code:You can fix this by writing your own copy constructor and assignment functions to correctly initialize
x
:This is safe, because
x
andy
will only be destroyed along with your object. Invalidation of references forstd::vector
means references to the vector elements: