【发布时间】:2014-09-01 20:32:33
【问题描述】:
第一个例子:
#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 构造函数。
让我们删除移动构造函数并添加一个副本:
#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&&)’”
所以 MOVE 构造函数是必需的,并且没有回退到 COPY 构造函数。
现在让我们删除复制和移动构造函数:
#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++ 标准以及在复制/移动构造函数之间进行选择的实际规则是什么?
【问题讨论】:
-
半小时前我不是已经回答了这个问题吗?>.>
-
这个问题要具体得多。这不是同一个问题。
标签: c++ c++11 copy-constructor move-constructor