std::unique_ptr可以通过数组特化版本std::unique_ptr<t[]>安全管理动态数组,自动调用delete[]释放内存;2. 必须使用t[]作为模板参数,否则使用std::unique_ptr<t>管理数组会导致未定义行为;3. 该特化版本支持operator[]访问元素,但不支持自定义删除器、动态扩容或直接获取大小;4. 尽管可用,但大多数场景应优先使用std::vector或std::array以获得更完整的容器功能和安全性。

智能指针能否管理数组?可以,但方式有限。C++标准库中的
std::unique_ptr
std::shared_ptr
std::unique_ptr
我们重点来看
std::unique_ptr
unique_ptr
std::unique_ptr
std::unique_ptr<T>
std::unique_ptr<T[]>
当你使用
T[]
unique_ptr
delete[]
delete
#include <memory>
#include <iostream>
int main() {
// 创建一个管理10个int的unique_ptr数组
std::unique_ptr<int[]> arr(new int[10]);
// 赋值
for (int i = 0; i < 10; ++i) {
arr[i] = i * i;
}
// 访问元素
for (int i = 0; i < 10; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// 离开作用域时自动调用 delete[]
return 0;
}注意:
new[]
int[]
int
operator[]
delete[]
如果不使用数组特化,比如写成:
std::unique_ptr<int> p(new int[10]); // 错误!
这会导致:
delete
delete[]
delete
而
std::unique_ptr<int[]>
delete[]
unique_ptr
虽然
unique_ptr<T[]>
shared_ptr
std::size()
std::begin
std::end
不过,它仍然比裸指针安全得多。
std::vector
std::array
虽然
unique_ptr<T[]>
std::vector<T>
std::array<T, N>
例如:
std::vector<int> arr(10); // 更现代、更安全
只有在以下情况才考虑
unique_ptr<T[]>
vector
new[]
std::unique_ptr<T[]>
delete[]
operator[]
std::unique_ptr<T>
std::vector
std::array
基本上就这些。用对了特化版本,
unique_ptr
以上就是智能指针能管理数组吗 unique_ptr数组特化版本使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号