【发布时间】:2014-07-10 14:05:52
【问题描述】:
为什么?!为什么 C++ 要求类是可移动的,即使它没有被使用! 例如:
#include <iostream>
using namespace std;
struct A {
const int idx;
// It could not be compileld if I comment out the next line and uncomment
// the line after the next but the moving constructor is NOT called anyway!
A(A&& a) : idx(a.idx) { cout<<"Moving constructor with idx="<<idx<<endl; }
// A(A&& a) = delete;
A(const int i) : idx(i) { cout<<"Constructor with idx="<<i<<endl; }
~A() { cout<<"Destructor with idx="<<idx<<endl; }
};
int main()
{
A a[2] = { 0, 1 };
return 0;
}
输出是(没有调用移动构造函数!):
idx=0 的构造函数
idx=1 的构造函数
idx=1 的析构函数
idx=0 的析构函数
如果移动构造函数被删除,则代码无法编译('使用已删除的函数'A::A(A&&)''。但如果构造函数没有被删除,它就不会被使用! 多么愚蠢的限制? 笔记: 为什么我需要它?当我尝试初始化包含 unique_ptr 字段的对象数组时,就会出现实际意义。 例如:
// The array of this class can not be initialized!
class B {
unique_ptr<int> ref;
public:
B(int* ptr) : ref(ptr)
{ }
}
// The next class can not be even compiled!
class C {
B arrayOfB[2] = { NULL, NULL };
}
如果您尝试使用 unique_ptr 的向量,情况会变得更糟。
好的。非常感谢大家。所有那些复制/移动构造函数和数组初始化都有很大的混淆。实际上,问题是关于编译器需要复制构造器,可能使用移动构造器并且不使用它们的情况。 因此,稍后当我获得普通键盘时,我将创建一个新问题。我会在这里提供链接。
附注我已经提出了更具体和明确的问题 - 欢迎来到discuss它!
【问题讨论】:
-
C++ 不要求类在不移动的情况下是可移动的。你跳到了错误的结论。
-
不不不...它需要一个移动的构造函数,但它不使用它。所以类没有移动,但需要构造函数。我的结论有什么问题?
-
不不不,你错了。
-
好的。让我们一步一步来。 1) 班级搬家了吗? 2) 是否需要移动构造函数?