从构造函数的初始化列表中捕获异常

2021-12-17 00:00:00 exception c++

这是一个奇怪的问题.我有一个 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
}

相关文章