How to declare the virtual destructor without breaking move and copy constructors

可紊 提交于 2019-12-06 05:37:13

问题


When adding a user defined default virtual destructor to a class like this..

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

.. It has the side effects of preventing auto generation of move constructors. Also auto generation of copy constructors is deprecated. A recommended way is to user define all constructors like this..

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;
};

However, this is super verbose and unreadable. Are there any other solutions to this?


回答1:


First I would consider whether Foo really needs a virtual destructor. Maybe you can solve your problem in a type safe manner using a simple template, saving you from messing with pointers and casting and so on.

If you decide on making Foo virtual, then I would recommend this abstraction.

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;
};

Put this in a library in an appropriate namespace. Then you can keep Foo and all other virtual classes clean.

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

The same technique can also be used when deleting for example copy constructors.

Edit: Compiler output and diff with original code



来源:https://stackoverflow.com/questions/35127608/how-to-declare-the-virtual-destructor-without-breaking-move-and-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!