这是一个好奇的.我有一个A类.它有一个B类项目,我想在A的构造函数中使用初始化列表初始化,如下所示:
class A {
public:
A(const B& b): mB(b) { };
private:
B mB;
};
Run Code Online (Sandbox Code Playgroud)
有没有办法捕获mB的拷贝构造函数可能在使用初始化列表方法时抛出的异常?或者我是否必须在构造函数的大括号中初始化mB才能获得try/catch?
Ada*_*ght 87
阅读http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/)
编辑:经过更多的挖掘,这些被称为"功能尝试块".
在我去看之前,我承认我不知道这一点.你每天都学到东西!我不知道这是否是对我现在使用C++有多少,我缺乏C++知识或者经常使用拜占庭式功能的起诉书.好吧 - 我还是喜欢:)
为了确保人们不必跳转到另一个站点,构造函数的函数try块的语法结果是:
C::C()
try : init1(), ..., initn()
{
// Constructor
}
catch(...)
{
// Handle exception
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*urr 18
它不是特别漂亮:
A::A(const B& b) try : mB(b)
{
// constructor stuff
}
catch (/* exception type */)
{
// handle the exception
}
Run Code Online (Sandbox Code Playgroud)