关于c ++:使用受保护的析构函数删除对象

Delete object with a protected destructor

我对C++内存管理是相当新的。我知道每个类都应该有一个虚拟析构函数吗?找到了这个答案:

Every abstract class should either have a

  • protected destructor or
  • virtual destructor

If you've got a public non-virtual destructor, that's no good, since it allows users to delete through that pointer a derived object. Since as we all know, that's undefined behavior.

For a class not intended to delete through a pointer to it, there is no reason whatsoever to have a virtual destructor. It would not only waste resources, but more importantly it would give users a wrong hint. Just think about what crappy sense it would make to give std::iterator a virtual destructor.

所以我现在有了一个受保护的析构函数(我不是从类派生的)。

在另一个类中,虽然我有一个指向这个对象的指针。在我的构造函数中,我将给指针一个该类的"新"对象,在我的destroctor中,我想销毁它。

我该怎么做?如果析构函数不受保护,我会得到一个SEG错误(我不完全理解,但我意识到无论如何编程都很糟糕)。如果析构函数受到保护,我不知道如何删除对象。


您在上面的块中缺少术语"abstract"。abstract"的意思是,你不应该/拥有/一个类的对象。如果您有一个类中的对象,那么它几乎应该总是有一个公共析构函数。