当向这样的类添加用户定义的默认虚拟析构函数时..
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();
};
删除例如复制构造函数时也可以使用相同的技术。
关于c++ - 如何在不破坏移动和复制构造函数的情况下声明虚拟析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127608/