例如 code:
void SomeModule::doStuff()
{
// in the controller, "this" object of SomeModule is the "current module"
// now, if I want to switch over to a new Module, eg:
controller->setWorkingModule(new OtherModule());
// since the new "OtherModule" object will take the lead,
// I want to get rid of this "SomeModule" object:
delete this;
}
As long as you're careful, it's OK for an object to commit suicide (delete this).
答案是可以,只要你能够保证对象是动态分配的,并且在销毁之后不再使用它。
本文探讨了在C++中一个对象是否可以安全地自我销毁(即通过成员函数调用delete this)。文中给出了一段示例代码并分析了在特定条件下这种操作的可行性及其注意事项。

3705

被折叠的 条评论
为什么被折叠?



