std::unique_ptr可以通过数组特化版本std::unique_ptr

智能指针能否管理数组?可以,但方式有限。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]); // 错误!
这会导致:
千博企业网站管理系统个人版免费下载、免费使用、功能无限制,完全免费拥有(请尊重开发者版权,保留首页底部版权显示):内含Flash动画源码、Access数据库程序包、SQL数据库程序包。 千博企业网站管理系统个人版特点: 1.全站模块化操作,静态标签调用,更强扩展性… 千博企业网站系统个人版是一套基于.Net + Access(SQL)建站管理系统软件、不依赖于服务商特定空间、不需安装任何空间商组
0
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号