C++ <memory>
系统讲解现代 C++ 动态内存管理头文件 <memory>:unique_ptr、shared_ptr 与 weak_ptr 打破循环引用的 RAII 所有权模型,以及 std::allocator/allocator_traits 与 std::align 对齐工具。
学完这一章,你能够
- 系统讲解现代 C++ 动态内存管理头文件 <memory>:unique_ptr、shared_ptr 与 weak_ptr 打破循环引用的 RAII 所有权模型,以及 std::allocator/allocator_traits 与 std::align 对齐工具。
动态内存挑战与三大智能指针模型
直接手工配对 `new`/`delete` 极易在异常分支或复杂控制流中造成内存泄漏、悬垂(野)指针或重复释放。C++11 起,`<memory>` 头文件通过基于 RAII(资源获取即初始化)的智能指针家族将堆对象生命周期与作用域自动绑定:`std::unique_ptr` 表达**独占所有权**(不可拷贝、可移动,几乎零额外开销);`std::shared_ptr` 表达**共享所有权**(内部维护原子引用计数,最后一个持有者析构时自动释放对象);`std::weak_ptr` 表达**非拥有弱引用**(观察 `shared_ptr` 托管对象而不增加强引用计数,专门用于打破循环引用)。
实践中推荐优先使用工厂函数 `std::make_unique<T>(args...)`(C++14)与 `std::make_shared<T>(args...)`(C++11)构造智能指针,而非显式书写 `new`:不仅语法更简洁、具备更强的异常安全性,且 `make_shared` 还能将控制块与对象本体合并为单次堆分配。`unique_ptr` 离开作用域或经 `std::move` 转移后原指针自动置空;`shared_ptr` 拷贝时引用计数递增,所有副本析构归零后立即释放目标对象。
当双向链表节点 `Node` 或父子对象彼此持有 `std::shared_ptr` 时,双方引用计数互相锁定而无法归零,导致内存泄漏。将回指成员 `prev` 改为 `std::weak_ptr<Node>` 后,`node1->next = node2; node2->prev = node1;` 不再增加 `node1` 的强引用计数;访问弱引用目标时调用 `prev.lock()` 临时提升为 `shared_ptr`(若目标已释放则返回空指针,`expired()` 为 `true`),从而在作用域结束时安全销毁全部节点。
标准分配器 std::allocator 与内存对齐工具 std::align
`<memory>` 的另一大支柱是容器底层使用的分配器体系 `std::allocator<T>`,它将原始内存分配(`allocate`/`deallocate`)与对象构造析构解耦。需要注意版本演进:`std::allocator::construct()` 与 `destroy()` 成员函数已在 **C++17 弃用并在 C++20 移除**;现代 C++ 应统一通过 `std::allocator_traits<Alloc>::allocate/construct/destroy/deallocate` 来操作分配器,确保向前兼容。
针对 SIMD、内存池等需要特定边界对齐的底层场景,`<memory>` 提供 `std::align(alignment, size, ptr, space)`:给定缓冲区起始指针 `ptr` 与剩余字节数 `space`,它在不越界的前提下将 `ptr` 向前推进至满足 `alignment` 对齐且可容纳 `size` 字节的地址,并相应缩减 `space`;若剩余空间不足则返回 `nullptr`。综合运用智能指针、分配器特征与对齐工具,能够以高度安全且可控的方式完成现代 C++ 内存管理。
实测 C++17 unique_ptr/shared_ptr/weak_ptr 析构计数、allocator_traits 与 std::align
展开查看收起
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <memory>
#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 {
struct Tracker {
static int live;
int value;
explicit Tracker(int v) : value(v) { ++live; }
~Tracker() { --live; }
};
int Tracker::live = 0;
struct Node {
static int live;
int id;
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev;
explicit Node(int i) : id(i) { ++live; }
~Node() { --live; }
};
int Node::live = 0;
} // namespace
int main() {
std::vector<lab::Case> cases;
// Case 1: std::unique_ptr exclusive ownership and move semantics
bool c1 = false;
{
auto u1 = std::make_unique<Tracker>(99);
bool after_create = (Tracker::live == 1 && u1->value == 99);
auto u2 = std::move(u1);
bool after_move = (u1 == nullptr && u2 != nullptr && u2->value == 99 && Tracker::live == 1);
c1 = after_create && after_move;
}
c1 = c1 && (Tracker::live == 0);
cases.push_back({"unique_ptr_exclusive_ownership", lab::jbool(true), lab::jbool(c1), c1});
// Case 2: std::shared_ptr reference counting lifecycle
bool c2 = false;
{
auto s1 = std::make_shared<Tracker>(7);
bool count1 = (s1.use_count() == 1 && Tracker::live == 1);
bool count2 = false;
{
auto s2 = s1;
count2 = (s1.use_count() == 2 && s2.use_count() == 2 && s2->value == 7);
}
bool count_back = (s1.use_count() == 1 && Tracker::live == 1);
c2 = count1 && count2 && count_back;
}
c2 = c2 && (Tracker::live == 0);
cases.push_back({"shared_ptr_reference_counting", lab::jbool(true), lab::jbool(c2), c2});
// Case 3: std::weak_ptr breaks cyclic reference between Nodes
std::weak_ptr<Node> observer;
bool lock_ok = false;
{
auto n1 = std::make_shared<Node>(1);
auto n2 = std::make_shared<Node>(2);
n1->next = n2;
n2->prev = n1;
observer = n1;
auto locked = n2->prev.lock();
lock_ok = (locked != nullptr && locked->id == 1 && Node::live == 2);
}
bool c3 = lock_ok && (Node::live == 0) && observer.expired();
cases.push_back({"weak_ptr_breaks_cycle", lab::jbool(true), lab::jbool(c3), c3});
// Case 4: std::allocator via std::allocator_traits + std::align
std::allocator<int> alloc;
using Traits = std::allocator_traits<std::allocator<int>>;
int* p = Traits::allocate(alloc, 1);
Traits::construct(alloc, p, 42);
bool alloc_val_ok = (*p == 42);
Traits::destroy(alloc, p);
Traits::deallocate(alloc, p, 1);
alignas(16) char raw_buf[64];
void* ptr = raw_buf + 3; // intentionally misaligned
std::size_t space = sizeof(raw_buf) - 3;
void* aligned = std::align(16, sizeof(int), ptr, space);
bool align_ok = (aligned != nullptr) &&
(reinterpret_cast<std::uintptr_t>(aligned) % 16 == 0) &&
(aligned == ptr) && (space == 64 - 16);
bool c4 = alloc_val_ok && align_ok;
cases.push_back({"allocator_traits_and_std_align", lab::jbool(true), lab::jbool(c4), c4});
lab::emit(cases);
return 0;
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`std::weak_ptr` 不增加目标对象的强引用计数,打破了 `node1` 与 `node2` 之间强引用计数永不归零的闭环;访问前需调用 `prev.lock()` 获取临时 `std::shared_ptr` 并判空,以保证访问期间对象存活。