c++ - 对成员的 const 引用是否安全

标签 c++ reference member getter invalidation

如果我使用对另一个成员的 const 引用, 这个引用有可能失效吗?

class Class {
public:
    const int &x{y};
private:
    int y;
};

例如,当我在 vector 中使用此类的实例时 这会在 push_back 之后增加其容量。 根据标准,所有迭代器和引用都无效,如果 vector 必须增加其容量。引用之后还有效吗?

最佳答案

目前这是不安全的,因为当您复制 Class 的实例时,x 将引用复制对象的 y,而不是它自己的 y。您可以通过运行以下代码来查看:

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 来解决此问题:

Class (const Class& rhs) : x{y}, y{rhs.y} {}

这是安全的,因为xy 只会与您的对象一起被销毁。 std::vector 的引用无效意味着对 vector 元素的引用:

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

关于c++ - 对成员的 const 引用是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31913953/

相关文章:

c++ - 二维指针初始化

C++使用引用从多线程返回值

c++ - 具有无效值的初始化引用

c++ - 成员和指针

c++ - 有没有办法创建一个以成员函数或成员作为参数的函数?

c - 非类类型错误

c++ - 在内联汇编中调用用户定义的 C 函数

C++ CreateRemoteThread 访问冲突

laravel - 一般错误 : 1824 Failed to open the referenced table

c++ - 使用 boost 的 skewed_normal_distribution