c++ - 遍历 unique_ptr 拥有的内存会产生段错误

标签 c++ unique-ptr

为了不用记住删除,我们使用unique_ptr来管理内存。 我们的印象是我们可以在内存中写入和读取,只是删除取决于智能指针。但是,以下代码在 i=7220 上崩溃并出现段错误。

怎么了?

#include <memory>
using namespace std;

int main() {
  const uint32_t n = 40000000;
  uint64_t*p = new uint64_t[n]; // this works, but we have to delete the memory or leak
  for (int i = 0; i < n; i++)
    p[i] = i;

  unique_ptr<uint64_t> mem = make_unique<uint64_t>(n);

  uint64_t* p1 = mem.get();
  for (int i = 0; i < n; i++) // this crashes at i=7220
    p1[i] = i;

  return 0;
}

最佳答案

unique_ptr<uint64_t> mem = make_unique<uint64_t>(n);

这会使用值 n 动态分配 一个 uint64_t

你想要:

unique_ptr<uint64_t[]> mem = make_unique<uint64_t[]>(n);

这个特化分配一个 uint64_tarrayn 元素,并且有一个 operator[] 重载,它使以下成为可能:

for (int i = 0; i < n; i++)
    mem[i] = i;

因此,无需执行 uint64_t* p1 = mem.get();

关于c++ - 遍历 unique_ptr 拥有的内存会产生段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67927585/

相关文章:

c++ - ostream&...这里的 '&' 是什么?

c++ - std::unique_ptr 是基础对象的两倍大

c++ - std::unique_ptr 在虚拟析构函数上重置 SIGABRT

java - 将 std::unique_ptr 传递给 JNI

c++ - 如何告诉 g++ 编译器在哪里搜索包含文件?

c++ - 两个经过修饰的名称分解为相同的函数签名

c++ - 非模板化成员函数的 enable_if 用法

c++ - 使用 ReadDirectoryChangesW C++ 重命名文件夹后获取旧名称和新名称

c++ - make_unique完美转发

c++ - 如何使用 lambda 和函数作为 unique_ptr 的自定义删除器