unique_ptr是C++11引入的独占式智能指针,通过move语义转移所有权,不可复制,推荐使用make_unique创建,能自动释放资源防止内存泄漏,支持数组管理和自定义删除器,适用于独占资源管理场景。

unique_ptr 是 C++11 引入的一种智能指针,用于管理动态分配的对象,确保同一时间只有一个 unique_ptr 拥有该对象的所有权。当 unique_ptr 被销毁时,它所指向的对象也会被自动释放,防止内存泄漏。
创建一个 unique_ptr 通常使用 std::make_unique(C++14 起支持),这是最安全、推荐的方式:
#include <memory>
#include <iostream>
<p>int main() {
auto ptr = std::make_unique<int>(10);
std::cout << *ptr << "\n"; // 输出: 10</p><pre class='brush:php;toolbar:false;'>auto strPtr = std::make_unique<std::string>("Hello");
std::cout << *strPtr << "\n"; // 输出: Hello}
如果不能使用 C++14,可以用 new 显式构造(不推荐):
立即学习“C++免费学习笔记(深入)”;
std::unique_ptr<int> ptr(new int(5));
unique_ptr 不允许拷贝,因为所有权必须唯一:
auto ptr1 = std::make_unique<int>(5); // auto ptr2 = ptr1; // 错误:不能复制 auto ptr2 = std::move(ptr1); // 正确:转移所有权
执行 std::move 后,ptr1 变为 nullptr,不再拥有资源,ptr2 成为新的所有者。
传递 unique_ptr 到函数时,通常使用移动语义或引用:
void usePtr(std::unique_ptr<int>& p) {
std::cout << *p << "\n";
}
<p>std::unique_ptr<int> createPtr() {
return std::make_unique<int>(42);
}</p><p>int main() {
auto ptr = std::make_unique<int>(7);
usePtr(ptr); // 通过引用传递,不转移所有权</p><pre class='brush:php;toolbar:false;'>auto newPtr = createPtr(); // 接收返回的 unique_ptr}
如果要管理动态数组,需指定数组类型:
auto arr = std::make_unique<int[]>(10); // 创建长度为10的数组 arr[0] = 1; arr[1] = 2; // 自动调用 delete[] 释放
注意:不能用 std::make_unique 初始化数组元素值,只能分配空间。
可以为 unique_ptr 指定自定义的释放逻辑,比如关闭文件、释放非内存资源:
void closeFile(FILE* f) {
if (f) fclose(f);
}
<p>auto file = std::unique_ptr<FILE, decltype(&closeFile)>(fopen("test.txt", "r"), &closeFile);</p>当 file 离开作用域时,会自动调用 closeFile。
基本上就这些。unique_ptr 简单高效,适合绝大多数需要独占所有权的场景。只要记住:不能复制,可用 move 转移,优先用 make_unique 创建。不复杂但容易忽略细节。
以上就是c++++中unique_ptr怎么使用_unique_ptr智能指针用法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号