【发布时间】:2018-01-26 23:56:00
【问题描述】:
为了正确处理对象复制,经验法则是Rule of Three。对于 C++11,移动语义是一回事,所以它是 Rule of Five。但是,在围绕here 和互联网的讨论中,我还看到了对Rule of Four (and a half) 的引用,它是五规则和复制和交换习语的组合。
那么究竟什么是四规则(半规则)?需要实现哪些功能,每个功能的主体应该是什么样的?哪个功能是一半?与五法则相比,这种方法有什么缺点或警告吗?
这是一个类似于我当前代码的参考实现。如果这是不正确的,正确的实现应该是什么样的?
//I understand that in this example, I could just use `std::unique_ptr`.
//Just assume it's a more complex resource.
#include <utility>
class Foo {
public:
//We must have a default constructor so we can swap during copy construction.
//It need not be useful, but it should be swappable and deconstructable.
//It can be private, if it's not truly a valid state for the object.
Foo() : resource(nullptr) {}
//Normal constructor, acquire resource
Foo(int value) : resource(new int(value)) {}
//Copy constructor
Foo(Foo const& other) {
//Copy the resource here.
resource = new int(*other.resource);
}
//Move constructor
//Delegates to default constructor to put us in safe state.
Foo(Foo&& other) : Foo() {
swap(other);
}
//Assignment
Foo& operator=(Foo other) {
swap(other);
return *this;
}
//Destructor
~Foo() {
//Free the resource here.
//We must handle the default state that can appear from the copy ctor.
//(The if is not technically needed here. `delete nullptr` is safe.)
if (resource != nullptr) delete resource;
}
//Swap
void swap(Foo& other) {
using std::swap;
//Swap the resource between instances here.
swap(resource, other.resource);
}
//Swap for ADL
friend void swap(Foo& left, Foo& right) {
left.swap(right);
}
private:
int* resource;
};
【问题讨论】:
-
不需要
if (resource != nullptr) delete resource;中的if。 -
由于您不应该使用原始的、拥有的指针,因此很少需要编写自己的析构函数。坦率地说:我不再相信 0、3、4、5、6 的任何一条规则。我尝试以一种只需要编写尽可能少的特殊成员函数的方式编写我的类。
-
@MikeMB 这是 0 的规则
-
@jpfx1342:如果不清楚,抱歉。我的评论是为了回答 4 半规则是什么问题(有时你需要 dtor -> 5,有时你不需要 -> 4)。因为这只回答了问题的一部分,所以我没有回答。
-
与大多数玩具示例一样,很难得出任何一般性结论。例如,为什么有人会存储
int*然后想要深拷贝?拥有一个“无用”的默认构造函数似乎不是最好的主意,特别是如果它只是用于一个奇怪的移动构造函数 - 这将在std::swap内构造另一个对象。似乎不是移动构造函数应该进行的明显速度优化。此外,当交换移动分配对象时,可能调用std::swap的赋值运算符似乎是递归的......
标签: c++ c++11 copy-constructor assignment-operator copy-and-swap