gpt4 book ai didi

c++ - 在 C++ 中模仿 Java try/finally 是否有一个受欢迎的习语?

转载 作者:IT老高 更新时间:2023-10-28 21:34:28 25 4
gpt4 key购买 nike

从事 Java 多年,所以一直没有跟踪 C++。 finally 子句是否已添加到语言定义中的 C++ 异常处理中?

是否有模仿 Java 的 try/finally 的流行习语?

我还担心 C++ 没有针对所有可能抛出的异常的终极父类(super class)型——比如 Java 的 Throwable 类。

我会写:

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

附录编辑:

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.

新的附录编辑:

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++?

最佳答案

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

这与 Java 不同,Java 中您不知道何时调用对象的终结器。

更新:直接从马口中:Why doesn't C++ provide a "finally" construct?

关于c++ - 在 C++ 中模仿 Java try/finally 是否有一个受欢迎的习语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/500244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com