ScopeGuard 解雇
我的代码需要范围防护,但是我是否必须在正常退出函数时手动 Dismiss()
所有范围防护? IE
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;
}
My code needs scope guards, however do I have to manually Dismiss()
all the scope guards on exit from a function normally? i.e.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须在函数结束后解除您想要保持活动状态的对象的守卫。否则,他们将各自删除他们所守护的对象。
You have to dismiss the guards for the objects you want to stay alive after the function. Otherwise they will each delete the object they are guarding.
鉴于 ScopeGuard 的此实现,那么答案是肯定的。对象删除将在 ScopeGuard 的析构函数中发生,除非您通过调用 Dismiss 方法禁用它。
Given this implementation of ScopeGuard, then the answer is yes. The object deletion will happen in the destructor of the ScopeGuard, unless you disable it by calling the Dismiss method.