第一个例子:
#include <iostream>
#include <memory>
using namespace std;
struct A {
unique_ptr<int> ref;
A(const A&) = delete;
A(A&&) = default;
A(const int i) : ref(new int(i)) { }
~A() = default;
};
int main()
{
A a[2] = { 0, 1 };
return 0;
}
它完美地运作。因此,在这里使用了MOVE构造函数。
让我们移除MOVE构造函数并添加一个复制构造函数:
#include <iostream>
#include <memory>
using namespace std;
struct A {
unique_ptr<int> ref;
A(const A&a)
: ref( a.ref.get() ? new int(*a.ref) : nullptr )
{ }
A(A&&) = delete;
A(const int i) : ref(new int(i)) { }
~A() = default;
};
int main()
{
A a[2] = { 0, 1 };
return 0;
}
现在编译出现错误 "use of deleted function ‘A::A(A&&)’"
因此需要移动构造函数,不能退回到复制构造函数。
现在我们将删除复制和移动构造函数:
#include <iostream>
#include <memory>
using namespace std;
struct A {
unique_ptr<int> ref;
A(const int i) : ref(new int(i)) { }
~A() = default;
};
int main()
{
A a[2] = { 0, 1 };
return 0;
}
编译器报错时会提示“use of deleted function ‘A::A(const A&)’”,这意味着现在需要一个COPY构造函数!
所以现在必须从移动构造函数退回到复制构造函数。
为什么?有没有人知道它如何符合C++标准,以及在选择复制/移动构造函数时实际上的规则是什么?