我有一个带有明确删除的复制构造函数的类,比方说,NonCopyable
。然后是一个 Base1
类,其成员类型为 NonCopyable
。另一个以 Base1
为父级的 Base2
类。最后 - 一个 Derivative
类,父类是 Base2
。
由于 NonCopyable
是不可复制的,很明显 Base1
、Base2
和 Derivative
也将是不可复制的-可复制。但似乎也删除了 move 构造函数(和赋值运算符)。
在这里测试:
下一行给出了这些错误:
派生 d1, d2 = std::move(d1);
GCC: 'Derived::Derived(Derived&&)' is implicitly deleted because the default definition would be ill-formed: class Derived :
the rest of errors just claims thatBase1
andBase2
copy ctors are implicitly deleted which is not weirdMSVC: error C2280: 'Derived::Derived(const Derived &)': attempting to reference a deleted function
在提供的链接中,也有给出类似错误的注释行。请取消注释它们以查看我想向您展示的更多错误(例如 remove_if
取消注释它提示删除的 move (在 GCC 上)/copy (在 MSVC 上) 赋值运算符)。
我想要实现的是使 Derivative (及其基础)可 move ,但不可复制。
我正在使用 Visual Studio 2015 并得到与我提供的 msvc 链接中完全相同的错误,但我不确定在 rextester.com 上使用哪个版本的 MSVC 进行编译.
应@Richard Critten 的要求,我也将代码粘贴在这里:
class NonCopyable
{
public:
NonCopyable() { }
NonCopyable(const NonCopyable &) = delete;
NonCopyable & operator=(const NonCopyable &) = delete;
NonCopyable(NonCopyable &&) { }
NonCopyable & operator=(NonCopyable &&) { return *this; }
};
class Base1
{
public:
virtual ~Base1() = default;
private:
NonCopyable m;
};
class Base2 :
public Base1
{
public:
virtual ~Base2() = default;
};
class Derived :
public Base2
{
};
int main()
{
std::vector<Derived> v;
//std::remove_if(v.begin(), v.end(), [](const Derived &) { return true; });
//v.emplace_back();
Derived d1, d2 = std::move(d1);
}
最佳答案
[class.copy]/9 If the definition of a class
X
does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if(9.4) —
X
does not have a user-declared destructor.
Base1
有一个用户声明的析构函数,所以它没有 move 构造函数。由于不可复制的成员,复制构造函数被隐式声明为已删除。所以 Base1
既不能复制也不能 move ,当然 Base2
和 Derived
也是一起的。
关于c++ - 不合理删除的 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42596060/