有没有喜欢的成语模仿Java的try / finally在C ++? [英] Is there a favored idiom for mimicing Java's try/finally in C++?

查看:261
本文介绍了有没有喜欢的成语模仿Java的try / finally在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做了多年的Java,所以没有跟踪C ++。在语言定义中是否已将 最后子句添加到C ++异常处理中?



Java的try / finally?



我还打扰C ++没有一个超级类型的所有可能抛出的异常,像Java的Throwable类。



我可以写:

  try {
// do something
} catch(...){
//唉,不能检查异常
//只能做清除代码,可能是rethrow,ala:
throw;
}

ADDENDUM EDIT:


我最终接受了
有最多投票的答案,即使用
析构函数来清理。当然,
从我自己的意见,很明显我
不完全同意。
然而,C ++是什么,因此在
应用程序努力我在
心里,我要或多或少努力坚持共同的社会
$ b练习。我将使用模板类来获得没有
a类析构函数(即C库
资源)的
包装资源,从而赋予它们
析构函数语义。 p>

新增添加项编辑


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



解决方案

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



这不同于Java

UPDATE :直接从马的嘴:为什么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的try / finally在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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