相关疑难解决方法(0)

是否允许删除?

是否允许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

225
推荐指数
8
解决办法
10万
查看次数

std::unique_ptr reset() 操作顺序

呼唤void reset( pointer ptr = pointer() ) noexcept; 会调用以下操作

\n
\n

给定 current_ptr(由 *this 管理的指针),按以下顺序执行以下操作:

\n
    \n
  1. 保存当前指针的副本 old_ptr = current_ptr
  2. \n
  3. 使用参数 current_ptr = ptr 覆盖当前指针
  4. \n
  5. 如果旧指针非空,则删除先前管理的对象 if(old_ptr) get_deleter()(old_ptr)。
  6. \n
\n
\n

参考参数

\n

这个特殊命令的原因是什么?为什么不先执行 3),然后再执行 2)?在这个问题中std::unique_ptr::reset 检查托管指针无效?第一个答案引用了标准

\n
\n

[\xe2\x80\xa6] [ 注意:这些操作的顺序很重要,因为调用 get_deleter() 可能会破坏 *this。\xe2\x80\x94结束注]

\n
\n

这是唯一的原因吗?怎么能get_deleter()毁掉unique_ptr*this )呢?

\n

c++ unique-ptr

10
推荐指数
1
解决办法
1888
查看次数