ScopeGuard使用真的导致更好的代码吗? [英] Does ScopeGuard use really lead to better code?

查看:147
本文介绍了ScopeGuard使用真的导致更好的代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了Andrei Alexandrescu和Petru Marginean多年前撰写的这篇文章,其中介绍和讨论了一个实用程序类称为ScopeGuard用于编写异常安全代码。我想知道如果编码与这些对象真正导致更好的代码或如果它混淆错误处理,也许守卫的回调将更好地呈现在catch块中?有没有人在实际生产代码中使用这些代码?

I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?

推荐答案

你的初步构成的声明,它是晦涩的和代码将是一个 catch 块是不是真的在C + +,因为RAII是一个成熟的习语。 C ++中的资源处理是通过资源获取完成的,而垃圾收集是通过隐式析构函数调用完成的。

It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a catch block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ is done by resource acquisition and garbage collection is done by implicit destructor calls.

另一方面, $ c> catch 阻塞会使代码膨胀,并引入微妙的错误,因为代码流变得非常复杂,并且必须明确地进行资源处理。

On the other hand, explicit catch blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly.

RAII(包括 ScopeGuard s)在C ++中不是一种模糊的技术,但坚定地建立了最佳实践。

RAII (including ScopeGuards) isn't an obscure technique in C++ but firmly established best-practice.

这篇关于ScopeGuard使用真的导致更好的代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆