c++ - 指向动态数组的 auto_ptr

标签 c++ auto-ptr

在我的代码中,我使用 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/

相关文章:

c++ - 通过函数时的 unique_ptr 行为

c++ - vector<auto_ptr<>> 的编译问题

c++ - 将 auto_ptr 作为参数传递给构造函数

c++ - 使用另一个类构造函数来初始化类

c++ - 虚拟内存地址在哪里?

c++ - RemoveDuplicates 仅在位置为 1 和 2 时删除

c++ - opencv连接细线

c++ - openmp Linux 中的段错误

c++ - 使用 C++ 将指针传递给 auto_ptr