c++ - 当派生定义了析构函数时,使用复制构造函数而不是移动构造函数

标签 c++ gcc

当我向派生类添加析构函数时,当它尝试使用复制构造函数而不是定义的移动构造函数时,我会遇到编译器错误(使用 gcc 4.7):

#include <utility>
#include <iostream>

template <typename T>
struct Base 
{
  T value;

  Base(T&& value) :
    value(value)
  {
    std::cout << "base ctor" << std::endl;
  }

  Base& operator=(const Base&) = delete;
  Base(const Base&) = delete;

  Base& operator=(Base&& rhs)
  {
    value = rhs.value;
    std::cout << "move assignment" << std::endl;
  }

  Base(Base&& other) :
    value(other.value)
  {
    std::cout << "move ctor" << std::endl;
  }

  virtual ~Base()
  {
    std::cout << "base dtor" << std::endl;
  }
};

template <typename T>
struct Derived : public Base<T>
{
  Derived(T&& value) :
    Base<T>(std::forward<T>(value))
  {
    std::cout << "derived ctor" << std::endl;
  }

  ~Derived()
  {
    std::cout << "derived dtor" << std::endl;
  }
};

template <typename T>
Derived<T> MakeDerived(T&& value)
{
  return Derived<T>(std::forward<T>(value));
}

struct Dummy {};

int main()
{
  auto test = MakeDerived(Dummy());
}

此代码在 gcc-4.5 和 gcc-4.6 上编译良好。 gcc-4.7 的错误是:

test.cpp: In function ‘int main()’:
test.cpp:61:34: error: use of deleted function ‘Derived<Dummy>::Derived(const Derived<Dummy>&)’
test.cpp:37:8: note: ‘Derived<Dummy>::Derived(const Derived<Dummy>&)’ is implicitly deleted because the default definition would be ill-formed:
test.cpp:37:8: error: use of deleted function ‘Base<T>::Base(const Base<T>&) [with T = Dummy; Base<T> = Base<Dummy>]’
test.cpp:16:3: error: declared here
test.cpp: In instantiation of ‘Derived<T> MakeDerived(T&&) [with T = Dummy]’:
test.cpp:61:34:   required from here
test.cpp:54:43: error: use of deleted function ‘Derived<Dummy>::Derived(const Derived<Dummy>&)’

我是不是遗漏了什么,或者这在 gcc 4.7 上也能正常编译吗?当我注释掉 Derived 类的析构函数时,一切都很好。

gcc version 4.5.3 (Ubuntu/Linaro 4.5.3-12ubuntu2) 
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 
gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-11precise2) 

最佳答案

错误正确;移动构造函数仅在类没有用户定义的析构函数时隐式生成。如果您添加一个析构函数,那么您将抑制默认的移动构造函数,并尝试使用复制构造函数。当一个类有一个不可复制的基类时,默认复制构造函数的生成被抑制,就像你的一样,所以 Derived 既不可复制也不可移动。

解决方案是简单地向 Derived 添加一个移动构造函数。

关于c++ - 当派生定义了析构函数时,使用复制构造函数而不是移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15306764/

相关文章:

gcc - Eclipse 无法识别 ARM Windows GCC 工具链的 stdint.h 中的类型

c++ - 模板类中没有名为 X 的类模板

c++ - 如何读带空格的名字?

c++ - 如何初始化一个有n个默认值的队列?

c++ - 如何处理我的 C++ __getitem__ 函数中的切片(由 SWIG 使用)

c++ - 为什么 C++ 模板编译器不能从协变智能指针参数推断类型?

c++ - 关于矢量化和循环大小的令人费解的 GCC 行为

c++ - std :shared_ptr in libstdc++ correct 的原子交换是怎样的

C 代码在带有 Windows 的 Turbo C 上运行时工作正常,但在 gcc Linux 中进入无限循环

android - 为什么 arm-linux-androideabi-gcc 给出 iostream 错误