std::shared_ptr类型的Vector不能释放内存

Vector of std::shared_ptr not freeing memory

本文关键字:Vector 不能 内存 释放 类型 shared ptr std      更新时间:2023-10-16

第一次在这里发帖,我不是一个CS的家伙,所以请原谅我。我有一个合适大小的代码,所以我将在下面发布我的问题的概要版本,然后解释它。

#include <vector>
#include <memory>
class A{
public: 
  A(){};
  double dbl[20];
};
typedef std::shared_ptr<A> A_ptr;
class B{
  public:
  const std::vector<A_ptr> createAVector(){
    std::vector<A_ptr> vec;
    for(int i=0; i<4; i++){
      vec.push_back(A_ptr( new A() ));
    }
    return vec;
  }
};
int myfunc(){
  // Do Stuff...
  std::vector<A_ptr> globvec;
  B b;
  for(int i=0; i<1e6; i++){
    const std::vector<A_ptr> locvec = b.createAVector();
    for(int i=0; i<locvec.size(); i++) globvec.push_back(locvec[i]);
  }
  globvec.clear();
  globvec.shrink_to_fit();
  // Do more stuff...
  return 1;
}

int main(){
  myfunc();
  for(auto i=0; i<3; i++){
    myfunc();
  }
  return 1;
}

编辑:我修改了代码,所以它实际上可以编译。

基本上我有两个类。类A存储实际数据。类B创建一个std::shared_ptrs到a的向量并返回它。然后,我在一个名为myfunc的函数中将这些局部向量组装成一个大的全局向量。为了测试当我想收缩globA的大小时是否释放了内存,我调用了globA.clear()和globA.shrink_to_fit()。

问题是调用clear()和shrink_to_fit()并不能释放所有创建的A的内存。

我在这里做了什么明显的错误吗?知道是怎么回事吗?

任何帮助都将是非常感激的。

谢谢!

约翰

您的代码很好。你基本上可以"证明"你没有泄漏A对象…(我还必须从1e6开始减少迭代次数,以获得合理的运行时间)。

有更复杂的工具来查找内存泄漏。我知道我们在Linux上使用Valgrind。但是,我不知道Windows对应的是什么。

class A{
public: 
  A() { std::cout << "Created A " << ++num_instances << std::endl;}
  ~A() { std::cout << "Destroyed A " << --num_instances << std::endl;}
  static int num_instances; // So not thread-safe
  double dbl[20];
};
int A::num_instances = 0;
相关文章: