构造函数参数列表后面的try是什么意思?

问题描述 投票:0回答:2

不久前我在一个SO问题中看到了特殊的语法。

class B{
    A a;
    public:
        B() try : a() {} catch(string& s) { cout << &s << " " << s << endl; };
};

函数外的这个try-catch块是什么意思?

c++ syntax try-catch member-initialization
2个回答
10
投票

它是函数try块。仅在 c-tor 中用于捕获派生类构造函数中的错误。您可以在标准中阅读有关此功能的更多信息,例如 n3337 草稿标准。 15, 15.1.

4 函数 try 块将 handler-seq 与 构造函数初始化程序(如果存在)和复合语句。一个例外 在执行复合语句期间抛出,或者,for 构造函数和析构函数,在初始化或 分别销毁该类的子对象,传输 控制函数 try 块中的处理程序的方式与 try 块执行期间抛出的异常转移控制权 给其他处理程序。 [ 示例:

int f(int);
class C {
int i;
double d;
public:
C(int, double);
};
C::C(int ii, double id)
try : i(f(ii)), d(id) {
// constructor statements
}
catch (...) {
// handles exceptions thrown from the ctor-initializer
// and from the constructor statements
}

—示例结束]


0
投票

它捕获创建成员对象时从构造函数抛出的异常。您提到的问题的答案之一包含一个解释详细信息的链接:http://www.gotw.ca/gotw/066.htm

© www.soinside.com 2019 - 2024. All rights reserved.