gpt4 book ai didi

c++ - "delete this"是个坏主意吗?

转载 作者:IT老高 更新时间:2023-10-28 22:17:30 26 4
gpt4 key购买 nike

Possible Duplicate:
Is it safe to delete this?

我一直在做一些工作,该类旨在充当链表中的节点,我想我应该为该类提供自己的删除功能,而不是由管理类执行。所以基本上是这样的:

void Class::Delete() {
//Some cleanup code before deleting the object
delete this;
}

现在我已经对此进行了测试,它似乎工作正常,但我过去遇到过一个问题,即对象一直处于运行代码的中间,被删除,然后显然通过尝试使用不再存在的对象。

由于“删除这个”就在函数的末尾,它显然退出了函数并且工作正常,但是这种做法是一个坏主意吗?如果我不小心,这会在我脸上炸开吗?

最佳答案

FAQlite很好地回答了这个问题:

As long as you're careful, it's OK for an object to commit suicide (delete this).

Here's how I define "careful":

  1. You must be absolutely 100% positive sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
  2. You must be absolutely 100% positive sure that your member function will be the last member function invoked on this object.
  3. You must be absolutely 100% positive sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
  4. You must be absolutely 100% positive sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.

Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.

基本上,您需要像 delete 任何其他指针一样小心。但是,与显式声明的指针相比,成员函数自杀可能会出错的地方更多。

关于c++ - "delete this"是个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6339386/

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