在我的代码中,我使用 new 分配一个整数数组。之后,我将这个指针包装到一个 auto_ptr 中。我知道 auto_ptr 会自动调用它的析构函数。由于我的 auto_ptr 指向一个数组(使用 new 分配),该数组会与 auto_ptr 一起被删除还是会导致内存泄漏。这是我的示例代码。
std::auto_ptr<int> pointer;
void function()
{
int *array = new int[2];
array[0] = 10;
array[1] = 20;
pointer.reset((int*) array);
}
int _tmain(int argc, _TCHAR* argv[])
{
function();
return 0;
}
最佳答案
数组不会被正确删除。 auto_ptr
使用delete contained_item;
。对于数组,它需要使用 delete [] contained_item;
代替。结果是未定义的行为。
正如 James McNellis 所说,您真的需要 std::vector
在这里——没有 new
,没有 auto_ptr
,不用担心。
关于c++ - 指向动态数组的 auto_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17691902/