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我已经添加了更多信息,现在我想你可以知道他们的意思了。 –
你应该改变标题,看起来你是通过成员初始化列表来询问成员的初始化,而不是关于参数初始化。班级成员不是参数 –