template <typename T>
Blob<T>::Blob(std::initializer_list<T> il) try :
data(std::make_shared<std::vector<T>>(il)) {
/* empty body */
} catch(const std::bad_alloc &e) { handle_out_of_memory(e); }
C++入門第五版779頁說爲什麼初始化列表構造函數參數時,異常發生?
Notice that the keyword try appears before the colon that begins the constructor initializer list and before the curly brace that forms the (in this case empty) constructor function body. The catch associated with this try can be used to handle exceptions thrown either from within the member initialization list or from within the constructor body. It is worth noting that an exception can happen while initializing the constructor’s parameters. Such exceptions are not part of the function try block. The function try block handles only exceptions that occur once the constructor begins executing. As with any other function call, if an exception occurs during parameter initialization, that exception is part of the calling expression and is handled in the caller’s context.
我很困惑,不能想到的,當它發生在那裏/的情況下,任何人都可以給我 一個例子嗎?
從這種情況出發,很難通過「初始化構造函數的參數」知道它們的含義。必須評估* any函數調用的參數,這可能導致異常,尤其是如果這些參數是從函數調用派生的。 –
@MarkRansom我已經添加了更多信息,現在我想你可以知道他們的意思了。 –
你應該改變標題,看起來你是通過成員初始化列表來詢問成員的初始化,而不是關於參數初始化。班級成員不是參數 –