有没有一个习惯用于模仿Java的尝试/最终在C ++中的习惯? [英] Is there a favored idiom for mimicing Java's try/finally in C++?

查看:107
本文介绍了有没有一个习惯用于模仿Java的尝试/最终在C ++中的习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年来一直在做Java,所以没有跟踪C ++。已经将 终止 子句添加到语言定义中的C ++异常处理中?



是否有一个喜欢的成语模仿Java的try / finally?



我也感到困扰的是,C ++没有一个最终的超类型,可以抛出所有可能的异常 - 像Java的Throwable类。 >

我可以写:

  try {
// do something
} catch(...){
//唉,不能检查异常
//只能执行清理代码,也可以重新抛出,ala:
throw;
}

ADDENDUM编辑:


我最终接受
最多投票的答案,即使用
析构函数进行清理。当然,从我自己的评论,
,很明显我没有完全同意这一点。
但是,C ++是什么,所以在
应用程序努力我有
的心态,我要或多或少地努力
坚持普通社区
练习。我将使用模板类
包装资源,它们还没有
a类析构函数(即C库
资源),从而赋予它们
析构函数语义。 p>

新增ADDENDUM编辑:


嗯,而不是 终于 那么关闭
的功能呢?结合
ScopeGuard方法(参见下面的
答案之一)将是一种方式,以
完成清理任意
操作并访问清理
代码外部范围上下文。清理可以在Ruby编程中看到的成语中完成,在资源打开时它们提供清理块。
C ++不考虑
关闭功能?



解决方案

p>通过有效地使用析构函数。当try块中抛出异常时,在其中创建的任何对象将立即被破坏(因此调用它的析构函数)。



不需要调用对象的终结器。



更新:直线从马的嘴巴:为什么C ++不提供finally结构?


Been doing Java for number of years so haven't been tracking C++. Has finally clause been added to C++ exception handling in the language definition?

Is there a favored idiom that mimics Java's try/finally?

Am also bothered that C++ doesn't have an ultimate super type for all possible exceptions that could be thrown - like Java's Throwable class.

I can write:

try {
  // do something
} catch(...) {
  // alas, can't examine the exception
  // can only do cleanup code and perhaps rethrow, ala:
  throw;
}

ADDENDUM EDIT:

I ended up accepting the answer that had the most up votes, i.e., use destructors to do cleanup. Of course, from my own comments, it is clear I don't entirely agree with that. However, C++ is what it is and so in the application endeavor I have in mind, I'm going to more or less strive to adhere to common community practice. I'll use template classes to wrap resources that don't already have a class destructor (i.e., C library resources), thus bestowing on them destructor semantics.

NEW ADDENDUM EDIT:

Hmm, instead of finally then a closure feature perhaps? A closure combined with ScopeGuard approach (see one of the answers below) would be a way to accomplish cleanup with arbitrary actions and access to the cleanup code's outer scope context. Cleanup could be done in the idiom fashion that is seen in Ruby programming where they supply cleanup blocks when a resource is being opened. Isn't a closure feature being considered for C++?

解决方案

By making effective use of destructors. When an exception is thrown in a try block, any object created within it will be destroyed immediately (and hence its destructor called).

This is different from Java where you have no idea when an object's finalizer will be called.

UPDATE: Straight from the horse's mouth: Why doesn't C++ provide a "finally" construct?

这篇关于有没有一个习惯用于模仿Java的尝试/最终在C ++中的习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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