[原创]警惕AI的胡说八道——std::shared_ptr<int> p{ new int(100) };

std::shared_ptr p{ new int(100) };

AI回答说这个是生成了长度为100的数组:

实际上,这段代码是以下代码的智能指针写法:
int *p=new int;
*p=100;
其实长度只有1。

从C++20支持了智能指针的动态数组写法:
std::shared_ptr<int[]> sp2 = std::make_shared<int[200]>(10);
这个意思是创建长度为200的int数组,初始化值为10;
image
另外一种写法是
std::shared_ptr<int[]> sp2 = std::make_shared<int[]>(10);
这个意思是创建了长度为10的int数组。没有初始化(堆内存默认初始化为0).

为什么会有动态数组?
例如我们在栈中二维数组的写法是:
int a[10][10];
如果想内存分配在堆中,写法则是:
// 分配指针数组
int** array = new int*[rows];
// 为每行分配内存
for (int i = 0; i < rows; ++i) {
array[i] = new int[cols];
}
// 初始化数组
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
array[i][j] = 0; // 或者其他值
}
}
//释放数组
for (int i = 0; i < rows; ++i) {
delete [] array[i];
}

C++20提供动态数组,是一种安全快捷的写法。

最后:
学习C++智能指针要有一个思路:想想它的不安全写法是啥,这样才会更容易理解。

posted @ 2025-07-14 11:07  范哥范小飞  阅读(6)  评论(0)    收藏  举报