Catching exceptions from a constructor#39;s initializer list(从构造函数的初始化列表中捕获异常)
问题描述
这是一个奇怪的问题.我有一个 A 类.它有一个 B 类项目,我想在 A 的构造函数中使用初始化列表对其进行初始化,如下所示:
Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:
class A {
public:
A(const B& b): mB(b) { };
private:
B mB;
};
有没有办法在仍然使用初始化列表方法的同时捕获可能由 mB 的复制构造函数抛出的异常?或者我是否必须在构造函数的大括号内初始化 mB 才能进行 try/catch?
Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?
推荐答案
阅读http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/)
经过更多挖掘,这些被称为功能尝试块".
After more digging, these are called "Function try blocks".
我承认在我去看之前我也不知道这一点.你每天都会学到一些东西!我不知道这是否是对我这些天很少使用 C++、我缺乏 C++ 知识,或者语言中经常出现的拜占庭特性的控诉.嗯 - 我仍然喜欢它:)
I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :)
为了确保人们不必跳转到另一个站点,构造函数的 try 块的语法结果是:
To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be:
C::C()
try : init1(), ..., initn()
{
// Constructor
}
catch(...)
{
// Handle exception
}
这篇关于从构造函数的初始化列表中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从构造函数的初始化列表中捕获异常


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01