C++ <new>
详解 C++ 底层动态内存管理头文件 <new>:new/delete 与 new[]/delete[] 配对规则、std::nothrow 无异常分配、std::bad_alloc 异常捕获,以及定位 new(placement new)在预分配缓冲区上的用法。
学完这一章,你能够
- 详解 C++ 底层动态内存管理头文件 <new>:new/delete 与 new[]/delete[] 配对规则、std::nothrow 无异常分配、std::bad_alloc 异常捕获,以及定位 new(placement new)在预分配缓冲区上的用法。
<new> 头文件组件与 new/delete 核心语法
在 C++ 中,`new` 与 `delete` 表达式本身是语言内置运算符,而头文件 `<new>` 声明了底层全局分配/释放函数 `operator new`、`operator delete`、无异常标签常量 **`std::nothrow`**、内存分配失败异常 **`std::bad_alloc`**(以及 `std::new_handler`、定位 `new` 和 C++17 的 `std::align_val_t`/`std::launder`)。
使用 `new` 在自由存储区(堆)动态创建单个对象的标准语法为 `Type* pointer = new Type(initializer);`(若省略初始化参数则默认初始化);释放单个对象必须使用 `delete pointer;`。动态创建数组使用 `Type* arr = new Type[count];`,释放数组**必须**配对使用 `delete[] arr;`——混用 `delete` 与 `new[]` 属于未定义行为。对空指针 `nullptr` 执行 `delete` 或 `delete[]` 是安全空操作。
单对象、数组、std::nothrow 与 std::bad_alloc 异常处理
在单对象示例中,`MyClass* myObject = new MyClass;` 在堆上分配内存并调用默认构造函数,随后通过**箭头运算符 `->`** 访问成员(`myObject->value = 10`),最后由 `delete myObject;` 调用析构函数并归还内存。在数组示例中,`int* myArray = new int[10];` 分配连续 10 个整数并按 `i * 2` 初始化为 `0, 2, ..., 18`,使用完毕以 `delete[] myArray;` 释放整块数组内存。
当系统无法满足内存请求时,默认 `new` 表达式会抛出 `std::bad_alloc` 异常,调用方可通过 `try { ... } catch (const std::bad_alloc& e)` 捕获并降级处理。在禁用异常或需显式判空的底层模块中,可使用带标签的 `new (std::nothrow) Type[n]` 形式:分配失败时不抛异常,而是返回 `nullptr`,调用方必须检查指针非空后再访问。此外,`<new>` 还支持定位 `new`(`new (aligned_buf) MyClass(args)`)在已有对齐内存上直接构造对象,析构时需显式调用 `obj->~MyClass()` 且不得 `delete` 栈缓冲区;日常业务代码仍建议优先选用 `std::vector` 与 `std::unique_ptr` 自动托管内存。
实测 <new> 单对象/数组配对释放、std::nothrow 判空、std::bad_alloc 与 placement new
展开查看收起
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <limits>
#include <new>
#include <string>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
namespace {
class MyClass {
public:
static int constructed;
static int destroyed;
int value;
explicit MyClass(int v = 0) : value(v) { ++constructed; }
~MyClass() { ++destroyed; }
};
int MyClass::constructed = 0;
int MyClass::destroyed = 0;
} // namespace
int main() {
std::vector<lab::Case> cases;
// Case 1: Single object new / delete
MyClass* obj = new MyClass;
obj->value = 10;
bool mid = (obj->value == 10 && MyClass::constructed == 1 && MyClass::destroyed == 0);
delete obj;
bool c1 = mid && (MyClass::destroyed == 1);
cases.push_back({"single_object_new_delete", lab::jbool(true), lab::jbool(c1), c1});
// Case 2: Dynamic array new[] / delete[]
int* arr = new int[10];
int sum = 0;
for (int i = 0; i < 10; ++i) {
arr[i] = i * 2;
sum += arr[i];
}
bool c2 = (arr[0] == 0 && arr[9] == 18 && sum == 90);
delete[] arr;
cases.push_back({"dynamic_array_new_delete", lab::jbool(true), lab::jbool(c2), c2});
// Case 3: std::nothrow returns nullptr and default new throws std::bad_alloc
volatile std::size_t impossible_size = std::numeric_limits<std::size_t>::max() / 2;
char* p_nothrow = new (std::nothrow) char[static_cast<std::size_t>(impossible_size)];
bool nothrow_null = (p_nothrow == nullptr);
if (p_nothrow) delete[] p_nothrow;
bool caught_bad_alloc = false;
try {
char* p_throw = new char[static_cast<std::size_t>(impossible_size)];
delete[] p_throw;
} catch (const std::bad_alloc& e) {
caught_bad_alloc = (std::strlen(e.what()) > 0);
}
bool c3 = nothrow_null && caught_bad_alloc;
cases.push_back({"nothrow_allocation_and_bad_alloc", lab::jbool(true), lab::jbool(c3), c3});
// Case 4: Placement new on aligned stack buffer + explicit destructor call
alignas(MyClass) unsigned char storage[sizeof(MyClass)];
MyClass* placed = new (storage) MyClass(77);
bool placed_ok = (placed->value == 77) && (reinterpret_cast<unsigned char*>(placed) == storage);
int before_d = MyClass::destroyed;
placed->~MyClass();
bool c4 = placed_ok && (MyClass::destroyed == before_d + 1);
cases.push_back({"placement_new_on_aligned_buffer", lab::jbool(true), lab::jbool(c4), c4});
lab::emit(cases);
return 0;
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
失败时 `new (std::nothrow)` 返回 `nullptr` 而普通 `new` 抛出 `std::bad_alloc`;`new[]` 与 `delete[]` 配对负责对数组每个元素调用析构函数并按数组分配协议回收内存,混用 `delete` 会导致未定义行为。