vendredi 27 février 2015

vector of unique_ptr not being fully deleted (memory leaks)

I'm writing a program that will eventually require me to create a vector of unique_ptrs to objects of a custom class. I was getting some memory leaks, so I decided to remove the custom class from the equation and just try it with unique_ptr.


When I try creating a unique_ptr on the stack, there are no leaks. However, creating a vector of unique_ptrs does leak. For fun, I also tried moving a unique_ptr into the vector just to see what happened. My code is below (includes MSVS memory checking):



#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

#include <vector>
#include <memory>
using namespace std;

int main()
{
vector<unique_ptr<int>> testvector;
unique_ptr<int> addMe;

testvector.emplace_back(move(addMe));
testvector.clear();

_CrtDumpMemoryLeaks();
return 0;
}


When I comment out everything except the creation of "addMe", I get no leaks.

When I comment out everything except the creation of "testvector", I get a memory leak of 8 bytes.

When I comment out the emplace_back of "addme" to "testvector", I get a memory leak of 8 bytes.

When I comment out nothing, I get a memory leak of 12 bytes.

Everything behaves the same when I replace all "unique_ptr" with "shared_ptr".


Am I doing something wrong, or is this to be expected with vectors of smart pointers?


Thanks!


Aucun commentaire:

Enregistrer un commentaire