C++ 内存管理:高级技巧与智能指针的运用
1. nothrow 版本的 new 运算符
在 C++ 中, new() 和 delete() 运算符允许抛出异常。当内存分配失败时,默认的 new 运算符会抛出 std::bad_alloc 异常,而不是返回 nullptr 。但在某些系统编程场景中,不希望因无效分配而抛出异常,为此,C++ 提供了 nothrow 版本的 new 运算符。
以下是使用 nothrow 版本 new 运算符的示例:
#include <iostream>
int main()
{
auto ptr = new (std::nothrow) int;
std::cout << ptr << '\n';
delete ptr;
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// 0x55893e230e70
使用 new (std::nothrow) 代替 new() ,这样在内存分配失败时会返回 nullptr ,而不是抛出 std::bad_alloc 异常。同时,
超级会员免费看
订阅专栏 解锁全文
905

被折叠的 条评论
为什么被折叠?



