unique_ptr 调用重置时数组崩溃
unique_ptr with array crash when calling reset
有人可以解释这里的崩溃吗?
#include <iostream>
#include <memory>
int main() {
int *num1 = new int(5), *num2 = new int(18);
std::unique_ptr<int> numptr = std::unique_ptr<int>(num1);
std::cout << *numptr.get() << '\n'; // 5
numptr.reset(num2);
std::cout << *numptr.get() << '\n'; // 18
int a[5] = {0,2,4,6,8}, b[5] = {0,3,6,9,12};
std::unique_ptr<int[]> u = std::unique_ptr<int[]>(a);
std::cout << u[3] << '\n'; // 6
u.reset(b);
std::cout << u[3] << '\n'; // Crash. Why??? Should output 9, right?
}
用std::unique_ptr<int>
调用reset没有崩溃,为什么用std::unique_ptr<int[]>
调用reset就崩溃了。如我所见,u
取得 b
的所有权,然后删除 a
。所以 u[3]
应该是 b[3] = 9
应该可以正常工作,因为 b
没有被删除。这里发生了什么?
您将 unique_ptr
包裹在一个数组中,该数组具有自动存储持续时间并且其内存将由运行时释放。在程序结束时,unique_ptr
尝试释放相同的内存。基本上,行 u.reset(b);
等同于 delete[] a; // then set u to point to b
。
如果你尝试像
这样的简单程序
int main()
{
int arr[10];
delete[] arr; // runtime error here
}
你会得到完全相同的错误。永远不要对非动态对象使用智能指针。
有人可以解释这里的崩溃吗?
#include <iostream>
#include <memory>
int main() {
int *num1 = new int(5), *num2 = new int(18);
std::unique_ptr<int> numptr = std::unique_ptr<int>(num1);
std::cout << *numptr.get() << '\n'; // 5
numptr.reset(num2);
std::cout << *numptr.get() << '\n'; // 18
int a[5] = {0,2,4,6,8}, b[5] = {0,3,6,9,12};
std::unique_ptr<int[]> u = std::unique_ptr<int[]>(a);
std::cout << u[3] << '\n'; // 6
u.reset(b);
std::cout << u[3] << '\n'; // Crash. Why??? Should output 9, right?
}
用std::unique_ptr<int>
调用reset没有崩溃,为什么用std::unique_ptr<int[]>
调用reset就崩溃了。如我所见,u
取得 b
的所有权,然后删除 a
。所以 u[3]
应该是 b[3] = 9
应该可以正常工作,因为 b
没有被删除。这里发生了什么?
您将 unique_ptr
包裹在一个数组中,该数组具有自动存储持续时间并且其内存将由运行时释放。在程序结束时,unique_ptr
尝试释放相同的内存。基本上,行 u.reset(b);
等同于 delete[] a; // then set u to point to b
。
如果你尝试像
这样的简单程序int main()
{
int arr[10];
delete[] arr; // runtime error here
}
你会得到完全相同的错误。永远不要对非动态对象使用智能指针。