c++ - 如果类具有引用成员,为什么合成的复制赋值运算符被定义为已删除?

标签 c++ c++11

在 C++ Primer,第五版,§13.1.6 中:

The synthesized copy-assignment operator is defined as deleted if a member has a deleted or inaccessible copy-assignment operator, or if the class has a const or reference member.

本章解释:

Although we can assign a new value to a reference, doing so changes the value of the object to which the reference refers. If the copy-assignment operator were synthesized for such classes, the left-hand operand would continue to refer to the same object as it did before the assignment. It would not refer to the same object as the right-hand operand. Because this behavior is unlikely to be desired, the synthesized copy-assignment operator is defined as deleted if the class has a reference member.

复制类会更改引用成员所引用的对象。这不是想要的吗?为什么解释说“不太可能被期望”?

具体来说,

class A {
public:
    A(int &n) : a(n) {}
private:
    int &a;
};

int main() {
    int n = 1;

    A a(n);

    /* Why is this allowed? */
    A b(a);

    /*
    Why is this not allowed?
    error C2280: 'A &A::operator =(const A &)': attempting to reference a deleted function
    */
    b = a;

    return 0;
}

最佳答案

引用一旦创建就无法重新分配。这意味着如果类包含引用成员,则不可能进行正确的赋值运算符。

复制构造函数是另一回事,因为引用可以在对象创建时分配。

关于c++ - 如果类具有引用成员,为什么合成的复制赋值运算符被定义为已删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48635366/

相关文章:

c++ - 匹配别名模板作为模板参数

c++ - 从 std::vector 到 mongo 数组

c++ - 模板参数的引用变量的问题

c++ - 以下程序背后的逻辑是什么?

c++ - 获取类中的字段数

c++ - 使用 Win32 线程模型时,MinGW-w64 是否支持开箱即用的 std::thread?

c++ - 为什么 std::list 中的单参数构造函数定义为显式

c++ - 一般打印光栅和/或 vector 图像

c++ - 初始化不可复制和不可移动类的元组

c# - 结合 C++ 和 C#