成员的const引用是否安全 [英] Are const references to members safe
问题描述
如果我使用const引用另一个成员, 此引用是否有可能无效?
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;
};
例如,当我在矢量中使用此类的实例时
在push_back
之后增加其容量.
根据标准,如果满足以下条件,则所有迭代器和引用均无效
载体必须增加其容量.此后引用仍然有效吗?
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?
推荐答案
当前不安全,因为当您复制Class
的实例时,x
会引用复制对象的y
,而不是其对象拥有y
.您可以通过运行以下代码来查看此内容:
This is currently not safe, as when you copy an instance of Class
, x
will reference the y
of the copied object, not its own y
. You can see this by running the following code:
int main()
{
Class a{};
std::vector<Class> vec;
vec.push_back(a);
//these lines print the same address
std::cout << &(a.x) << std::endl;
std::cout << &(vec[0].x) << std::endl;
}
您可以通过编写自己的副本构造函数和赋值函数来正确初始化x
来解决此问题:
You can fix this by writing your own copy constructor and assignment functions to correctly initialize x
:
Class (const Class& rhs) : x{y}, y{rhs.y} {}
这是安全的,因为x
和y
只会与您的对象一起被销毁.对std::vector
的引用无效意味着对矢量元素的引用:
This is safe, becausex
and y
will only be destroyed along with your object. Invalidation of references for std::vector
means references to the vector elements:
Class c;
std::vector<Class> vec;
vec.push_back(c);
Class& cr = vec[0];
//other operations on vec
std::cout << c.x; //fine, that reference is internal to the class
std::cout << cr.x; //cr could have been invalidated
这篇关于成员的const引用是否安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!