std::unique_ptr通过模板特化支持数组管理,需使用T[]语法确保析构时调用delete[];声明如std::unique_ptr<int[]> ptr(new int[10]),C++14起可用std::make_unique<int>(10)创建,默认初始化且不支持列表初始化;正确特化避免未定义行为,支持下标访问与指针算术,是安全高效的动态数组管理方式。

在C++中,使用智能指针管理动态分配的数组时,std::unique_ptr 提供了对数组的特化支持,可以安全地管理数组资源,避免内存泄漏。虽然
std::unique_ptr
delete[]
delete
要让
std::unique_ptr
T[]
std::unique_ptr<int[]> ptr(new int[10]);
std::unique_ptr<double[]> dptr = std::make_unique<double[]>(5);
std::make_unique
注意:如果不写
[]
std::unique_ptr<int>
delete
delete[]
数组特化的
unique_ptr
立即学习“C++免费学习笔记(深入)”;
ptr[0] = 42;
int val = ptr[5];
它也支持指针算术,因为底层是指向数组首元素的指针。
C++区分单个对象和数组的内存释放方式:
delete
delete[]
std::unique_ptr<T[]>
delete[]
C++14 起,
std::make_unique
auto arr = std::make_unique<int[]>(10); // 创建10个int的数组
auto zero_arr = std::make_unique<int[]>(0); // 也可以创建0大小数组
注意:不能用
make_unique
{1,2,3}基本上就这些。使用
std::unique_ptr<T[]>
[]
以上就是C++智能指针管理数组 unique_ptr数组特化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号