問題描述
這是一個奇怪的問題.我有一個 A 類.它有一個 B 類項目,我想在 A 的構(gòu)造函數(shù)中使用初始化列表對其進(jìn)行初始化,如下所示:
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 的復(fù)制構(gòu)造函數(shù)拋出的異常?或者我是否必須在構(gòu)造函數(shù)的大括號內(nèi)初始化 mB 才能進(jìn)行 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/)
經(jīng)過更多挖掘,這些被稱為功能嘗試塊".
After more digging, these are called "Function try blocks".
我承認(rèn)在我去看之前我也不知道這一點(diǎn).你每天都會學(xué)到一些東西!我不知道這是否是對我這些天很少使用 C++、我缺乏 C++ 知識,或者語言中經(jīng)常出現(xiàn)的拜占庭特性的控訴.嗯 - 我仍然喜歡它:)
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 :)
為了確保人們不必跳轉(zhuǎn)到另一個站點(diǎn),構(gòu)造函數(shù)的 try 塊的語法結(jié)果是:
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
}
這篇關(guān)于從構(gòu)造函數(shù)的初始化列表中捕獲異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!