gpt4 book ai didi

c++ - 如果 new 抛出 std::bad_alloc,是否将指针设置为 NULL?

转载 作者:搜寻专家 更新时间:2023-10-31 00:21:14 25 4
gpt4 key购买 nike

我知道执行 new(std::no_throw) 会在失败时将指针设置为 NULL。我也知道,如果失败,普通的 new 将抛出 std::bad_alloc 异常。

如果正常的 new 抛出,是否也会将指针设置为 NULL?或者我应该在 catch() block 中将它设置为 NULL 吗?

最佳答案

在 C++ 中,错误的 new 将抛出异常(除非您使用 std::nothrow)并且不会分配指针,因此它将是 new< 之前的任何内容 已调用。

但是,您可能对 this article 感兴趣正如您在问题中提到的那样,它谈到了强制 new 在失败时返回 null 。

关于c++ - 如果 new 抛出 std::bad_alloc,是否将指针设置为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4845192/

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