简体   繁体   中英

Vector of std::shared_ptr not freeing memory

First time posting on here, and I'm not a CS guy, so please bear with me. I have a good sized, code, so I will post a bare-bones version of my problem below and then explain it.

#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;
}

Edit: I modified the code so it actually compiles.

So, basically I have two classes. Class A stores the actual data. Class B, among other things, creats a vector of std::shared_ptrs to A and returns it. I then assemble these local vectors into a large global vector in a function called myfunc. To test that memory is freed when I want to shrink the size of globA, I call globA.clear() and globA.shrink_to_fit().

The problem is that calling clear() and shrink_to_fit() does not free the memory of all the A's created.

Am I doing something obviously wrong here? Any idea what might be going on?

Any help would be greatly appreciated.

Thanks!

John

Your code is fine. You can essentially 'prove' that you are not leaking A objects with this... (I also had to reduce the number of iterations from 1e6 to get any reasonable runtime).

There are more sophisticated tools for finding memory leaks. I know for Linux we use Valgrind. I don't know what the Windows equivalent is however.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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