4

考虑一下:

class FluffyThing
{
public:
  FluffyThing()
  {
    m_pMyFur = new Fur;
  }
  virtual ~FluffyThing();

protected:
  Fur * m_pMyFur;
};

class ClawedFluffyThing : public FluffyThing
{
public:
  ClawedFluffyThing()
    : FluffyThing()
  {
    m_pMyClaws = new Claws;
  }
  virtual ~ClawedFluffyThing();

protected:
  Claws * m_pMyClaws;
};

class ScaryFluffyThing : public ClawedFluffyThing
{
public:
  ScaryFluffyThing()
    : ClawedFluffyThing()
  {
    m_pMyTeeth = new Teeth;
    m_pMyCollar = new SpikedCollar;
  }
  virtual ~ScaryFluffyThing();

protected:
  Teeth * m_pMyTeeth;
  SpikedCollar * m_pMyCollar;
};

希望没有太多错误 - 我想你明白了。要点是它们之间存在 3 个具有 IS-A 关系的类,并且每个类还具有一两个在销毁时间方面需要清理的属性。如果我没有声明虚拟析构函数,编译器会自动为我生成以下内容吗?声明了析构函数,因此被迫实现它们(假设使用了类)是遵循正确的长期方法来进行破坏吗?

FluffyThing::~FluffyThing()
{
  delete m_pMyFur;
}

ClawedFluffyThing::~ClawedFluffyThing()
{
  delete m_pMyClaws;
  FluffyThing::~FluffyThing();
}

ScaryFluffyThing::~ScaryFluffyThing()
{
   delete m_pMyTeeth;
   delete m_pMyCollar;
   ClawedFluffyThing::~ClawedFluffyThing();
}

肯定已经有一个明确的答案......但我无法足够快地找到我喜欢的答案。

4

1 回答 1

4

不。您不会手动调用基类的析构函数,它们会以继承的相反顺序自动调用。除此之外,还好。

FluffyThing::~FluffyThing()
{
  delete m_pMyFur;
}

ClawedFluffyThing::~ClawedFluffyThing()
{
  delete m_pMyClaws;
} //will call ~FluffyThing

ScaryFluffyThing::~ScaryFluffyThing()
{
   delete m_pMyTeeth;
   delete m_pMyCollar;
}  //will call ~ClawedFluffyThing

当然,delete如果您使用 RAII(智能指针而不是原始指针),您甚至不需要 s。

如果我没有声明虚拟析构函数,编译器会自动为我生成以下内容吗?

不。:)virtual在您通过基类指针删除派生类实例的情况下,析构函数用于正确的行为。以下:

FluffyThing* p = new ScaryFluffyThing;
delete p;

仅当FluffyThing' 的析构函数是虚拟的时才合法。否则,这是未定义的行为。

于 2012-08-14T00:54:24.767 回答