gpt4 book ai didi

c++ - 使用 protected 析构函数删除对象

转载 作者:行者123 更新时间:2023-11-30 03:04:16 26 4
gpt4 key购买 nike

我对 C++ 内存管理还很陌生。我读了Should every class have a virtual destructor?并找到了这个答案:

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.

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

虽然我有一个指向这个对象的指针,但在另一个类中。在我的构造函数中,我为指针提供了该类的"new"对象,在我的析构函数中,我想销毁它。

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

最佳答案

您在上面的 block 中遗漏了术语“抽象”。 “抽象”意味着您不应该/拥有/该类的对象。如果你有一个类的对象,它几乎应该总是有一个公共(public)析构函数。

关于c++ - 使用 protected 析构函数删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8778153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com