简体   繁体   English

在 C++ 中,我可以在定义自己的复制构造函数后跳过定义赋值运算符吗?

[英]In C++, can I skip defining assignment operator after defining my own copy constructor?

When I define a class, I need to define my own copy constructor if I need deep-copy.当我定义一个类时,如果我需要深拷贝,我需要定义我自己的拷贝构造函数。 Then, is it necessary to define the assignment operator as well?那么,是否也需要定义赋值运算符呢? If it is skipped, does the assignment do shallow copy?如果跳过,赋值是否做浅拷贝?

Yes you need.是的,你需要。 This is known as the Rule of Three : when one of copy-ctor, assignment-operator or dtor is defined, the two others must probably be defined.这被称为三法则:当定义了 copy-ctor、assignment-operator 或 dtor 之一时,可能必须定义其他两个。 Exceptions exists but in standard cases, you must...存在例外,但在标准情况下,您必须...

Since C++11, Rule of Five applies to tackle the move semantics.从 C++11 开始, 五法则适用于处理移动语义。

It is generally preferable to define data members such that you don't need to write a copy constructor (nor a copy assignment operator).通常最好定义数据成员,这样您不需要编写复制构造函数(或复制赋值运算符)。

Instead of代替

class Foo {
    Bar * data = nullptr;
public:
    explicit Foo(const Bar & x) : data(new Bar(x)) {}
    ~Foo() { delete data; }
    Foo(const Foo & other) : data(new Bar(*other.data)) {}
    Foo& operator=(const Foo & other) { delete data; data = new Bar(*other.data); return *this; }
};

You have你有

class Foo {
    Bar data;
public:
    explicit Foo(const Bar & x) : data(x) {}
};

This is known as the Rule of Zero这被称为零规则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM