gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:38:07 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com