c++ 为什么声明复制构造函数不删除复制赋值运算符,反之亦然?

8yoxcaq7  于 2022-11-27  发布在  其他
关注(0)|答案(1)|浏览(420)

因此,如果我有一个类,并在其中声明了一个复制赋值操作符,显然,我希望在复制时有一些特殊的行为。我希望语言能帮助我,隐式删除复制构造函数,直到我显式地将其恢复,以避免在执行type instance = type()时出现与already_existing_instance = type()相反的非预期的不同行为。
无论如何,我们建议您在尝试声明复制构造函数和复制赋值运算符中的一个时,同时显式声明这两个操作符,这正是因为C++不会删除另一个,这会让您感到头疼。
我发现这很烦人的一个例子是删除复制赋值操作符。如果我想快速地使类不可复制,我希望删除复制赋值操作符可以达到这个目的,但是我还必须显式地删除复制构造函数。
我的问题是编译器为什么要这样做?谁认为这是个好主意?它所做的只是给程序员制造了一个不必要的障碍,还是我遗漏了什么?
P.S.在移动构造函数/赋值操作符时,这种行为不会出现,为什么在这种情况下要区分复制和移动呢?

uttx8gqw

uttx8gqw1#

不建议使用未删除的项目。

例如,给定-Wextra,发出铿锵声15

struct A
{
    A() {}
    A(const A &) {}
};

int main()
{
    A a, b;
    a = b;
}

吐口水

<source>:4:5: warning: definition of implicit copy assignment operator for 'A' is deprecated because it has a user-provided copy constructor [-Wdeprecated-copy-with-user-provided-copy]
    A(const A &) {}
    ^
<source>:10:7: note: in implicit copy assignment operator for 'A' first required here
    a = b;
      ^

同样地,

struct A
{
    A() {}
    A &operator=(const A &) {return *this;}
};

int main()
{
    A a, b(a);
}

给予

<source>:4:8: warning: definition of implicit copy constructor for 'A' is deprecated because it has a user-provided copy assignment operator [-Wdeprecated-copy-with-user-provided-copy]
    A &operator=(const A &) {return *this;}
       ^
<source>:9:10: note: in implicit copy constructor for 'A' first required here
    A a, b(a);
         ^

相关问题