user1275154
user1275154

Reputation: 1150

C++ std::map memory management

I have following C++ code

map<long, TelemInfoV01> LastTelemetry;

void UpdateTelemetry( const TelemInfoV01 &info )
{
    LastTelemetry[info.mID] = info;
}

where TelemInfoV01 is a struct

The UpdateTelemetry method is called outside of my code, passing a value, that I cache and use later. How does the map manage memory? Is it copying the struct in same way, do I have to delete it manually after removing from the global LastTelemetry map?

I do not control the scope of the 'info' variable coming into the method. I just want to cache it's value to use it in a different call.

The main reason for asking is that I have some memory leaks and would like to track it down.

Thanks, Stevo

Upvotes: 1

Views: 2184

Answers (2)

marcinj
marcinj

Reputation: 49976

The UpdateTelemetry method is called outside of my code, passing a value, that I cache and use later. How does the map manage memory?

map will keep its own copy of your class instances, if TelemInfoV01 is properly implemented then you dont have to worry about memory leaks. If you allocate some memory inside it then you must follow rule of three to prevent memory leaks, but its still better to put pointers inside smart pointers (the so called rule of zero).

Is it copying the struct in same way, do I have to delete it manually after removing from the global LastTelemetry map?

You dont have to worry, after you struct is removed from map, destructor will be called on it and it will be properly destroyed. So, to memory leak here you would have to allocate some bare pointer in your struct constructor, and then forget about deleting it in destructor.

If your cache is a global variable, then it will be destroyed once you return from your main. So if you check memory leaks befor main end, your cache might look like a memory leak.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

Q How does the map manage memory?

A map does not do anything special to manage memory.

Q Is it copying the struct in some way?

A Yes, it does.

The operator[] function of map is defined like:

mapped_type& operator[] (const key_type& k);

The expression LastTelemetry[info.mID] evaluates to TelemInfoV01&. That means the line

LastTelemetry[info.mID] = info;

is analogous to calling an assignment operator on TelemInfoV01 ( like a = b;). A copy of info is stored in the map.

Q Do I have to delete it manually after removing from the global LastTelemetry map?

A No. Since your map holds objects, they get destructed when the map gets destructed. Had you chosen to store pointers to TelemInfoV01 instead of objects, you'd have to take extra care to deallocate the memory.

Upvotes: 1

Related Questions