提问人:cathgreen 提问时间:12/3/2019 最后编辑:TonySalimicathgreen 更新时间:12/3/2019 访问量:140
在 C++ 中,在定义自己的复制构造函数后,我可以跳过定义赋值运算符吗?
In C++, can I skip defining assignment operator after defining my own copy constructor?
答:
5赞
Jean-Baptiste Yunès
12/3/2019
#1
是的,你需要。这被称为三法则:当定义 copy-ctor、assignment-operator 或 dtor 之一时,可能必须定义另外两个。存在例外情况,但在标准情况下,您必须...
从 C++ 11 开始,五法则适用于处理移动语义。
1赞
Caleth
12/3/2019
#2
通常,最好定义数据成员,这样就不需要编写复制构造函数(也不需要编写复制赋值运算符)。
而不是
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; }
};
你有
class Foo {
Bar data;
public:
explicit Foo(const Bar & x) : data(x) {}
};
这被称为零法则
评论