【问题标题】:Virtual Destructor needed when using Cloaking pattern?使用伪装模式时需要虚拟析构函数吗?
【发布时间】:2011-10-28 01:22:32
【问题描述】:

如果我有以下 3 个类来隐藏数据类型和存储信息, 我需要一个虚拟析构函数吗?我被引导相信不,但现在我不确定。 出于性能原因,如果可能的话,我宁愿不包括它。例如清酒类被剥离。

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

【问题讨论】:

    标签: c++ virtual-destructor cloaking


    【解决方案1】:

    对于auto_ptr,我认为您需要虚拟析构函数,因为delete 会以多态方式发生——换句话说,在内部auto_ptr 最终会在存储的DarkHideInterface* 上调用delete。如果DarkHideInterface 没有虚拟析构函数并且指针指向DarkHideInterfaceImpl 实例,那么您会得到未定义的行为。

    请注意,据我所知,您不需要带有 shared_ptr 的虚拟析构函数,因为它会记住构造它的指针的类型并直接在该指针上调用 delete(搜索“virtual析构函数'在这里看看我的意思:http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm)。

    【讨论】:

    • 谢谢,这对我来说很有意义。我想知道新 0x 标准中的 unique_ptr 是否会以同样的方式工作。
    猜你喜欢
    • 2010-10-15
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 2022-01-01
    相关资源
    最近更新 更多