简体   繁体   English

boost是否具有用于数组向量的智能指针?

[英]Does boost have smart pointers for a vector of arrays?

This is to hold a data like 这是为了保存像

double **a;
a = new (double*)[100];
for (int i=0; i<100; ++i) {
   a[i] = new double[99];
}

The ptr_vector can include a vector of pointers. ptr_vector可以包括指针的向量。 But it does not seem supporting customized deleter to free an array. 但是它似乎不支持自定义删除器来释放数组。

One solution is that I can create a new class that manages 99 doubles, and use ptr_vector to hold 100 of the classes? 一种解决方案是,我可以创建一个管理99个double的新类,并使用ptr_vector容纳100个类?

The best approach is to use the Standard Library . 最好的方法是使用标准库 std::vector saves you from having to worry about memory management and having to set the vector's size. std::vector您不必担心内存管理和设置向量的大小。

std::vector<std::vector<double>> a;

You can also use std::unique_ptr , but it is more bothersome to allocate dynamic memory. 您也可以使用std::unique_ptr ,但是分配动态内存更麻烦。 However, since it is a std::unique_ptr is a smart pointer when the object destructs/runs out of scope, memory is automatically deallocated. 但是,由于std :: unique_ptr是std :: unique_ptr是对象破坏/超出范围时的智能指针 ,因此会自动释放内存。

std::unique_ptr<std::unique_ptr<double>[]> a(new std::unique_ptr<double>[100]);
  for (i=0; i <100; i++)
      a[i] = std::unique_ptr<int[]>(new int[99]);

The above works, but it defeats the intent of std::unique_ptr which is to save you from using pointers and automatically allocating and deallocating memory. 上面的方法有效,但是它违反了std::unique_ptr的意图,该意图使您免于使用指针以及自动分配和释放内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM