Should C++ 'interfaces' have a virtual des

2019-03-11 14:26发布

Possible Duplicate:
Destructors for C++ Interface-like classes

Consider a simple example of a C++ abstract class, used to model an interface:

class IAnimal
{
  virtual void walk()=0;
  virtual ~IAnimal(){}
};

Is it better to have the destructor, or not? I don't think the destructor can be pure virtual, at least my tests give linker errors, so should an empty destructor be included?

EDIT: sorry, typo. It's a destructor not a constructor.

标签: c++
6条回答
劳资没心,怎么记你
2楼-- · 2019-03-11 14:56

an empty constructor should probably be included since a typical use of an interface involves putting a pointer to some concrete object in a container, which will otherwise call the wrong destructer and will not clean the memory correctly. so if anyone is going to delete derived objects through a pointer to Ianimal make a virtual destructor, else make your destructor nonvirtual and protected. making your destructor pure virtual is probably not such a good idea, since it forces implementers of derived classes to override your destructor, eventhough they might want to do nothing

查看更多
祖国的老花朵
3楼-- · 2019-03-11 15:01

You should always use a virtual destructor with interfaces. Case in point:

IAnimal* animal = new Lion();
delete animal;

Now what destructor is it going to use? Definately not the Lion's destructor because the interface doesn't know about Lion's destructor.

So, have this if your interface has no memory management:

virtual ~IAnimal(){}
查看更多
看我几分像从前
4楼-- · 2019-03-11 15:04

This depends on whether you intend to manage the lifetime of objects polymorphically, using pointers to the interface class.

If you do, then the destructor must be virtual, in order to correctly delete the objects. Deleting a base-class pointer that doesn't have a virtual destructor is invalid, and gives undefined behaviour.

If you don't, then you should enforce this by making the destructor non-virtual and protected, so only derived classes can be deleted.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-03-11 15:07

Check out this article by Herb Sutter

Especially this part:

For the special case of the destructor only:

Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.

This assumes that base class is an 'interface' class as it mostly should be.

查看更多
Summer. ? 凉城
6楼-- · 2019-03-11 15:09

I think it should be a pure virtual destructor for interfaces, and all other methods are pure virtual as well.

查看更多
萌系小妹纸
7楼-- · 2019-03-11 15:16

The only reason not to make the destructor virtual would be to save the space needed for the vptr. As you need the vptr anyway because you have another virtual function, I would make the destructor virtual.

查看更多
登录 后发表回答