c++ - 如何在不破坏移动和复制构造函数的情况下声明虚拟析构函数

标签 c++ c++11 virtual-destructor

当向这样的类添加用户定义的默认虚拟析构函数时..

class Foo
{
public:
    Foo();
    virtual ~Foo() = default;
};

.. 它具有阻止自动生成移动构造函数的副作用。复制构造函数的自动生成也被弃用。 A recommended way is to user define all constructors像这样..

class Foo
{
public:
  Foo();
  virtual ~Foo() = default;
  Foo(const Foo& /* other */) = default;
  Foo&operator=(const Foo& /* other */) = default;
  Foo(Foo&& /* other */) = default;
  Foo&operator=(Foo&& /* other */) = default;
};

但是,这非常冗长且难以阅读。还有其他解决方案吗?

最佳答案

首先我会考虑 Foo 是否真的需要一个虚拟析构函数。也许您可以使用一个简单的模板以类型安全的方式解决您的问题,避免弄乱指针和强制转换等。

如果您决定使 Foo 成为虚拟的,那么我会推荐这种抽象。

class VirtualDestructor
{
protected:
  VirtualDestructor() = default;
  virtual ~VirtualDestructor() = default;
  VirtualDestructor(const VirtualDestructor & /* other */) = default;
  VirtualDestructor &operator=(const VirtualDestructor & /* other */) = default;
  VirtualDestructor(VirtualDestructor && /* other */) = default;
  VirtualDestructor &operator=(VirtualDestructor && /* other */) = default;
};

将其放入适当命名空间 的库中。然后您可以保持 Foo 和所有其他虚拟类干净。

class Foo : VirtualDestructor
{
public:
    Foo();
};

删除例如复制构造函数时也可以使用相同的技术。

编辑: Compiler outputdiff with original code

关于c++ - 如何在不破坏移动和复制构造函数的情况下声明虚拟析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127608/

相关文章:

c++ - 是否有不关心结构/类布局的编译指示?如果不是,为什么?

c++ - 使用C++流式传输OpenCV mat数据

c++ - 为什么我不能用 const_iterator 调用模板基类构造函数?

c++ - 从具有非虚拟父类的虚拟类继承的正确方法(续)

c++ - 直接调用(虚拟)析构函数是否有效?

c++ - C++中的仅调试ostreams?

c++ - 类的透明聚合

c++ - 将 boost::thread 与 C++11 std::mutex 混合使用是否安全?

c++ - 如何使用 boost C++ 反序列化对和对象的 vector

c++ - 如果基类析构函数是虚拟的,是否需要派生类析构函数定义?