在C++开发中,手动使用new和delete管理动态内存常常引发泄漏或二次释放等问题。unique_ptr作为标准库提供的智能指针,依托RAII机制在对象离开作用域时自动析构并释放资源,从根本上简化了内存管理。它采用独占式所有权模型,不允许拷贝,只能通过移动转移控制权。

什么是RAII
RAII全称是资源获取即初始化,核心思路是将资源生命周期绑定到对象生命周期上。当对象构造时获取资源,析构时释放资源,从而利用栈对象自动回收的特性管理堆资源。
unique_ptr基本用法
使用unique_ptr需包含头文件<memory>。以下示例展示创建与自动释放过程:
#include <iostream>
#include <memory>
int main() {
// 创建独占智能指针,管理一个int对象
std::unique_ptr<int> p = std::make_unique<int>(42);
std::cout << *p << std::endl; // 解引用访问
// 离开作用域时自动delete,无需手动释放
return 0;
}
所有权转移
unique_ptr不能拷贝,但可通过std::move转移所有权。原指针随后变为空。
#include <memory>
void transfer(std::unique_ptr<int> ptr) {
// 接收所有权
}
int main() {
auto a = std::make_unique<int>(10);
auto b = std::move(a); // a不再拥有对象
transfer(std::move(b));
return 0;
}
自定义删除器
当资源不是普通new分配时,可指定删除器。例如用fclose关闭文件:
#include <memory>
#include <cstdio>
int main() {
std::unique_ptr<FILE, decltype(&fclose)> file(fopen("test.txt", "w"), fclose);
// 离开作用域自动fclose
return 0;
}
与数组配合使用
unique_ptr支持数组类型,释放时调用delete[]:
#include <memory>
int main() {
auto arr = std::make_unique<int[]>(5);
arr[0] = 1;
return 0;
}
总结
unique_ptr是C++现代内存管理的基石。结合RAII,它让动态资源具备确定性的释放时机,避免人为疏忽。在项目中应优先使用make_unique创建,并尽量以移动而非拷贝的方式传递,这样既安全又高效。
unique_ptrRAII内存管理修改时间:2026-07-27 19:42:16