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
}
这篇关于从构造函数的初始化列表中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从构造函数的初始化列表中捕获异常
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01