首页 > 后端开发 > C++ > 正文

c++中unique_ptr怎么使用_c++智能指针unique_ptr用法详解

裘德小鎮的故事
发布: 2025-10-12 13:21:02
原创
971人浏览过
std::unique_ptr是C++11引入的独占式智能指针,通过移动语义转移所有权,析构时自动释放资源,支持自定义删除器和数组管理,推荐使用std::make_unique创建,避免裸指针使用,提升内存安全。

c++中unique_ptr怎么使用_c++智能指针unique_ptr用法详解

std::unique_ptr 是 C++11 引入的一种智能指针,用于管理动态分配的对象,确保同一时间只有一个指针拥有该对象的所有权。当 unique_ptr 被销毁时,它所指向的对象也会自动被删除,从而避免内存泄漏。它不能被复制,但可以移动,适用于资源的独占式管理。

基本用法

创建一个 unique_ptr 非常简单,通常使用 std::make_unique(C++14 起支持)或直接构造:

  • 使用 std::make_unique 推荐方式:
#include <memory>
auto ptr = std::make_unique<int>(42);  // 创建一个指向 int 的 unique_ptr,值为 42
登录后复制
  • 手动构造(不推荐裸 new):
std::unique_ptr<int> ptr(new int(42));  // 可以,但不如 make_unique 安全
登录后复制

访问所指向对象使用 *ptrptr->,就像普通指针一样。

所有权转移(移动语义)

由于 unique_ptr 不可复制,但支持移动语义,可以通过 std::move 转移所有权:

立即学习C++免费学习笔记(深入)”;

std::unique_ptr<int> ptr1 = std::make_unique<int>(100);
std::unique_ptr<int> ptr2 = std::move(ptr1);  // ptr1 失去所有权,变为 nullptr
<p>if (ptr1 == nullptr) {
std::cout << "ptr1 is now null\n";
}
// 此时只有 ptr2 指向原来的对象</p>
登录后复制

移动后,原指针变为空,防止重复释放。

作为函数参数和返回值

unique_ptr 常用于函数间传递资源:

  • 函数返回 unique_ptr,移交所有权:
std::unique_ptr<int> createValue() {
    return std::make_unique<int>(99);
}
<p>auto val = createValue();  // 接收所有权</p>
                    <div class="aritcle_card">
                        <a class="aritcle_card_img" href="/ai/1906">
                            <img src="https://img.php.cn/upload/ai_manual/001/246/273/68b6d6a3864ff358.png" alt="Gnomic智能体平台">
                        </a>
                        <div class="aritcle_card_info">
                            <a href="/ai/1906">Gnomic智能体平台</a>
                            <p>国内首家无需魔法免费无限制使用的ChatGPT4.0,网站内设置了大量智能体供大家免费使用,还有五款语言大模型供大家免费使用~</p>
                            <div class="">
                                <img src="/static/images/card_xiazai.png" alt="Gnomic智能体平台">
                                <span>47</span>
                            </div>
                        </div>
                        <a href="/ai/1906" class="aritcle_card_btn">
                            <span>查看详情</span>
                            <img src="/static/images/cardxiayige-3.png" alt="Gnomic智能体平台">
                        </a>
                    </div>
                
登录后复制
  • 函数接收 unique_ptr 参数(通过移动):
void consume(std::unique_ptr<int> ptr) {
    std::cout << *ptr << "\n";
}  // ptr 在这里析构,对象被删除
<p>auto p = std::make_unique<int>(50);
consume(std::move(p));  // 必须用 move</p>
登录后复制

如果只是想查看内容而不获取所有权,应传 const 引用:const std::unique_ptr<T>&

自定义删除器

unique_ptr 支持自定义删除逻辑,比如关闭文件句柄、释放非 new 分配的资源等:

// 删除器为函数指针类型
void close_file(FILE* f) {
    if (f) fclose(f);
}
<p>std::unique_ptr<FILE, decltype(&close_file)> file(fopen("test.txt", "r"), &close_file);</p><p>// 使用 lambda 更灵活
auto deleter = [](int* p) {
std::cout << "Deleting int\n";
delete p;
};
std::unique_ptr<int, decltype(deleter)> custom_ptr(new int(42), deleter);</p>
登录后复制

管理数组

虽然更推荐使用 std::vectorstd::array,但 unique_ptr 也可以管理动态数组:

std::unique_ptr<int[]> arr = std::make_unique<int[]>(10);  // C++14 起支持
<p>arr[0] = 1;
arr[1] = 2;
// ... 使用中括号访问
// 析构时会自动调用 delete[]</p>
登录后复制

注意:数组版本不能使用 operator-> 或 *,只能用下标访问。

与 raw 指针交互

必要时可以获取原始指针,但要小心生命周期:

std::unique_ptr<int> ptr = std::make_unique<int>(77);
int* raw = ptr.get();  // 获取裸指针,不转移所有权
<p>// 重置或释放所有权
ptr.reset();      // 释放对象,ptr 变为 nullptr
ptr.reset(new int(88));  // 替换管理的对象</p><p>int* released = ptr.release();  // 释放所有权,返回裸指针,ptr 变空
delete released;  // 需手动 delete</p>
登录后复制

基本上就这些。unique_ptr 设计简洁高效,是现代 C++ 中替代裸指针和 auto_ptr 的首选,能极大提升代码安全性和可维护性。

以上就是c++++中unique_ptr怎么使用_c++智能指针unique_ptr用法详解的详细内容,更多请关注php中文网其它相关文章!

相关标签:
c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号