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++ - 堆栈怎么能是一个范围呢?

c++ - 如果不使用它,访问数组外的数据是否不正确?

c++ - 这个 auto_ptr 程序是如何工作的,它做了什么?

c++ - 为什么用execute::par对 vector 进行排序要比正常排序(gcc 10.1.0)花费更长的时间?

c++ - ‘{’ 之前的预期类名

c++ - OpenCV + CUDA + OSX 小牛队

c++ - Auto_ptr 到外部 C 结构

c++ - 为什么不推荐使用 auto_ptr?

c++ - boost::ptr_vector 和 boost::any 的问题

c++ - 如何在 Linux 上使用智能指针(例如 auto_ptr r shared_ptr)在 C++ 中生成链接列表数据结构?