c++ - 不合理删除的 move 构造函数

标签 c++ c++11 inheritance move-semantics

我有一个带有明确删除的复制构造函数的类,比方说,NonCopyable。然后是一个 Base1 类,其成员类型为 NonCopyable。另一个以 Base1 为父级的 Base2 类。最后 - 一个 Derivative 类,父类是 Base2

由于 NonCopyable 是不可复制的,很明显 Base1Base2Derivative 也将是不可复制的-可复制。但似乎也删除了 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 that Base1 and Base2 copy ctors are implicitly deleted which is not weird

MSVC: 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 ,当然 Base2Derived 也是一起的。

关于c++ - 不合理删除的 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42596060/

相关文章:

c++ - 使用类型别名,例如使用 A = int(int)

c++ - 使用函数分配内存时会发生什么?

python - 在派生类中传递 *args/**kwargs

r - 在 R 中, `is.list(x)` 和 `is(x,' 列表之间的不同行为')`

c++ - 帮助进行 rake 依赖映射

c++ - CMake 和 Visual Studio 项目设置

c++ - #ifdef Q_OS_WIN32,但 windows 函数未在此范围内声明

c++ - 找不到句首

C++:如何对 scoped_ptr 进行单元测试?

objective-c - 从另一个类获取整数值