c++++的智能指针中unique_ptr天然支持数组管理,而shared_ptr需要自定义删除器。1. unique_ptr通过声明数组类型如std::unique_ptr<int[]>可自动调用delete[]释放内存,推荐使用std::make_unique创建数组;2. shared_ptr默认不支持数组,必须手动提供删除器如lambda表达式确保调用delete[],可通过封装模板函数简化操作;3. 实际开发中,若需独占数组资源优先选unique_ptr,若需共享则用带删除器的shared_ptr,或考虑标准库容器如vector更安全便捷。

C++的智能指针确实可以管理数组,但不是所有智能指针都“天生”支持数组,需要特别注意用法。
unique_ptr
shared_ptr

unique_ptr
unique_ptr

std::unique_ptr<int[]> arr(new int[10]);
这样声明后,
unique_ptr
delete[]
delete
立即学习“C++免费学习笔记(深入)”;
unique_ptr<T[]>
unique_ptr<T>
delete
std::make_unique
auto arr = std::make_unique<int[]>(10);
shared_ptr
shared_ptr
delete[]
delete

不过你可以通过自定义删除器的方式来解决这个问题:
std::shared_ptr<int> arr(new int[10], [](int* p){ delete[] p; });这样就能确保数组被正确释放。
template<typename T>
using array_deleter = std::default_delete<T[]>;
template<typename T>
std::shared_ptr<T> make_array(size_t size) {
return std::shared_ptr<T>(new T[size], array_deleter<T>());
}在实际项目中,选择哪种智能指针管理数组,取决于你的需求:
unique_ptr<T[]>
shared_ptr
std::vector
std::array
基本上就这些。智能指针对数组的支持不算复杂,但容易因为疏忽导致问题,特别是
shared_ptr
unique_ptr<T[]>
shared_ptr
就不会踩坑了。
以上就是C++智能指针能管理数组吗 unique_ptr和shared_ptr对数组的支持的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号