c++ - 为什么初始化构造函数列表参数会出现异常?

标签 c++ c++11

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/

相关文章:

c++ - (共享)指向单例的指针

c++ - 为什么没有 std::make_function()?

c++ - 如何确保此 qi 解析器不允许点运算符之间有空格?

c++ - srand(time(0)) 和 rand() 导致堆栈溢出错误

c++ - experimental::optional "nullopt_t"命名原理

c++ - 为什么我收到以下错误 : "no match for ' operator= ='" ?(带有模板的嵌套类)

c++ - C++ 11 中 std::is_base_of 的逻辑

c++ - 谁能解释当前 C++0x 标准草案的这一段?

c++ - `thread_local` 全局变量什么时候初始化?

c++ - 未定义的函数引用 (c++)