nique_ptr是 C++11 引入的独占式智能指针,定义在<memory>头文件中,核心作用是自动管理动态分配的内存,避免内存泄漏,且保证同一时间只有一个指针拥有对对象的所有权。

核心特性

  1. 独占所有权同一时刻,仅有一个unique_ptr能指向同一个动态对象,禁止拷贝(拷贝构造和拷贝赋值被禁用),仅支持移动语义(通过std::move转移所有权)。
  2. 自动析构unique_ptr的生命周期结束(如离开作用域),其析构函数会自动调用delete,释放所管理的对象,无需手动释放内存。
  3. 支持数组专门提供unique_ptr<T[]>版本,适配动态数组的内存管理(会自动调用delete[])。
  4. 可自定义删除器可指定自定义函数 / 仿函数,用于替代默认的delete/delete[],适配特殊资源(如文件句柄、网络连接)的释放。

基本用法

1. 创建unique_ptr

cpp

运行

#include <memory>
#include <iostream>
using namespace std;

class Test {
public:
    Test() { cout << "Test created" << endl; }
    ~Test() { cout << "Test destroyed" << endl; }
};

int main() {
    // 方式1:C++14起推荐用make_unique(更安全,避免内存泄漏)
    unique_ptr<Test> ptr1 = make_unique<Test>();
    
    // 方式2:直接构造(不推荐,可能存在异常安全问题)
    unique_ptr<Test> ptr2(new Test());
    
    // 管理动态数组
    unique_ptr<int[]> arr_ptr(new int[5]{1,2,3,4,5});
    cout << arr_ptr[0] << endl; // 输出1
    
    return 0; // 作用域结束,ptr1、ptr2、arr_ptr自动析构,释放资源
}
2. 转移所有权

通过std::move将所有权从一个unique_ptr转移给另一个:

cpp

运行

unique_ptr<Test> ptr1 = make_unique<Test>();
unique_ptr<Test> ptr2 = std::move(ptr1); // ptr1失去所有权,变为空指针
if (ptr1 == nullptr) {
    cout << "ptr1 is null" << endl;
}
3. 常用成员函数
函数 作用
get() 返回指向对象的裸指针(仅用于访问,不转移所有权)
reset() 释放当前管理的对象,若传入新指针则接管新对象
release() 放弃对象所有权,返回裸指针(需手动释放)
swap() 交换两个unique_ptr管理的对象

示例:

cpp

运行

unique_ptr<Test> ptr = make_unique<Test>();
Test* raw_ptr = ptr.get(); // 获取裸指针
ptr.reset(); // 释放Test对象,ptr变为空
ptr.reset(new Test()); // 释放原有对象,接管新的Test对象
Test* released_ptr = ptr.release(); // 放弃所有权,需手动delete
delete released_ptr;
4. 自定义删除器

适配非内存资源的释放(如文件):

cpp

运行

// 自定义删除器:关闭文件
void closeFile(FILE* fp) {
    if (fp) {
        fclose(fp);
        cout << "File closed" << endl;
    }
}

int main() {
    // 接管文件指针,指定自定义删除器
    unique_ptr<FILE, decltype(&closeFile)> file_ptr(fopen("test.txt", "w"), closeFile);
    return 0; // 自动调用closeFile释放文件资源
}

注意事项

  1. 不要将同一个裸指针赋值给多个unique_ptr,否则会导致重复释放。
  2. 避免用unique_ptr管理栈上对象(析构时会调用delete,导致未定义行为)。
  3. 若需要共享所有权(多个指针指向同一对象),应使用shared_ptr而非unique_ptr
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐