c++ - ScopeGuard 解雇

标签 c++ scopeguard

我的代码需要范围守卫,但是我是否必须手动 Dismiss() 从函数正常退出时所有范围守卫?即

void Deleter(MyClass* obj)
{
    delete obj;
}

MyClass* Func()
{
    MyClass* obj = new MyClass();
    ScopeGuard sg1 = MakeObjGuard(Deleter, obj);

    //More objects created. And more scope guards.

    sg1.Dismiss();
    //...Same for other guards
    return obj;
}

最佳答案

你必须在函数结束后解散你想要存活的对象的守卫。否则他们将各自删除他们正在守卫的对象。

关于c++ - ScopeGuard 解雇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5269484/

相关文章:

c++ - 使用范围保护时如何避免警告?

c++ - 遍历数组指针?

c++ - 回到 C++,带指针的 void 函数,如何制作 get 函数

c++ - 使用 boost spirit x3 解析为具有 bool 值或枚举成员的结构

c++ - 从 'size_t' 转换为 'const double' ,可能丢失数据

c++ - 编译 qt Creator/qt widget 示例时出错

C++ : other one simple scope guard

c++ - 用于临时延长生命周期的 const 引用

c++ - 为什么 Alexandrescu 不能使用 std::uncaught_exception() 在 ScopeGuard11 中实现 SCOPE_FAIL?