Вопрос

If I have the following 3 classes to hide the data type and store information, do I need a virtual destructor? I was led to believe no, but now I am not sure. I would rather not include it if possible for preformance reasons. Classes stripped down for example sake.

#include <memory>

class DarkHideInterface
{
  public:
  bool test;

};


template <typename T>
class DarkHideInterfaceImpl : public DarkHideInterface
{
  public:
  DarkHideInterfaceImpl (const T& t )  : _t(t) {}

  private: 
  T _t; 
};


class DarkHide
{
  public:
  template <class T> DarkHide (const T& t) : p_(new DarkHideInterfaceImpl<T>(t) ) { } 

  private:
  std::auto_ptr<DarkHideInterface> p_; 
};
Это было полезно?

Решение

With auto_ptr, I think you need the virtual destructor, since the delete will happen polymorphically - in other words, internally auto_ptr will ultimately call delete on the stored DarkHideInterface*. If DarkHideInterface doesn't have a virtual destructor and the pointer points to a DarkHideInterfaceImpl instance, then you get undefined behaviour.

Note that you wouldn't need a virtual destructor with shared_ptr as far as I know, because that remembers the type of the pointer with which it was constructed and calls delete on that pointer directly (search for 'virtual destructor' here to see what I mean: http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top