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++ Primer第五版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.
我很困惑,想不出什么时候发生的情况,谁能给我 举个例子?
最佳答案
这是一个例子:
struct S
{
S(char *);
};
int main()
{
S s(new char[0x7FFFFFFF]);
}
new char[0x7FFFFFFF]
可能会抛出内存不足的异常。
关于c++ - 为什么初始化构造函数列表参数会出现异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42848656/