是否允许delete this;delete-statement是将在该类实例上执行的最后一个语句?当然,我确信this-pointer所代表的对象是newly-created.
我在考虑这样的事情:
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;
}
Run Code Online (Sandbox Code Playgroud)
我可以这样做吗?
c++ memory-management new-operator self-destruction delete-operator
呼唤void reset( pointer ptr = pointer() ) noexcept; 会调用以下操作
\n\n\n给定 current_ptr(由 *this 管理的指针),按以下顺序执行以下操作:
\n\n
\n- 保存当前指针的副本 old_ptr = current_ptr
\n- 使用参数 current_ptr = ptr 覆盖当前指针
\n- 如果旧指针非空,则删除先前管理的对象 if(old_ptr) get_deleter()(old_ptr)。
\n
这个特殊命令的原因是什么?为什么不先执行 3),然后再执行 2)?在这个问题中std::unique_ptr::reset 检查托管指针无效?第一个答案引用了标准
\n\n\n[\xe2\x80\xa6] [ 注意:这些操作的顺序很重要,因为调用 get_deleter() 可能会破坏 *this。\xe2\x80\x94结束注]
\n
这是唯一的原因吗?怎么能get_deleter()毁掉unique_ptr(*this )呢?