gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:15:04 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com