0

I am just learning C++, and I'm having some trouble with memory leaks. I am using Visual Studio express, and I have enabled the crtdbg commands to dump memory leaks when the program closes. I cannot for the life of me, though, see why this particular line is being marked as a memory leak.

I have a class for Resource, and it contains a

static std::unordered_map< std::string, std::unique_ptr < Resource >> RESOURCE_LIBRARY;

This contains the definitions of the available resources, and then a factory method makes new resources based on these definitions when new resources are needed.

I then have a method that populates this map like this:

std::unique_ptr< Resource > lResource = std::unique_ptr< Resource >(new Resource(0, 0));
Resource::RESOURCE_LIBRARY["blue"] = std::move(lResource);

The problem I am seeing is that these lines to populate the map are the source of the memory allocation that isn't cleared up, according to Visual Studio. I have tried a method to free this like this:

for (auto it = RESOURCE_SOURCE_LIBRARY.begin(); it != RESOURCE_SOURCE_LIBRARY.end(); it++)
{
    it->second.reset();
}

but I still get the same messages out. I am sure that I must be missing/misunderstanding something here, so any help would be appreciated.

Edit:
Here's an example:

#define _CRTDBG_MAP_ALLOC

#include <crtdbg.h>
#include <string>
#include <unordered_map>

class Resource
{
public:
    Resource(){};
    static std::unordered_map<std::string, Resource> LIBRARY;
};

std::unordered_map<std::string, Resource> Resource::LIBRARY;

int main()
{
    Resource lResource;
    Resource::LIBRARY["first"] = lResource;
    Resource::LIBRARY.clear();

    _CrtDumpMemoryLeaks();
}

This reports that the memory is allocated in the line

Resource::LIBRARY["first"] = lResource;
DCHE
  • 38
  • 1
  • 6
  • Can you show an [MCVE](http://stackoverflow.com/help/mcve)? – n. m. could be an AI Nov 28 '15 at 10:43
  • Is the `Resource` a class you have created? If so, why are you using smart pointers to hold its objects in the first place? Why don't you store by value instead? – Andy Nov 28 '15 at 10:44
  • [Possible duplicate](http://stackoverflow.com/questions/2323458/how-to-ignore-false-positive-memory-leaks-from-crtdumpmemoryleaks). – n. m. could be an AI Nov 28 '15 at 12:01
  • The static object `LIBRARY` is destroyed at the end of the program - roughly, at the closing brace of `main`. You are dumping memory before that - of course everything is still allocated at that time. – Igor Tandetnik Nov 28 '15 at 15:07

0 Answers0