Skip to main content
GameDev.net gamedev.net
🔒 Locked

Using STL Maps

Started by Vincent_M Sep 27, 2013 at 10:54 PM 7 replies 1.8k views
Original Post
Vincent_M
Vincent_M

If I have a map, and insert an element like so:


map::<string, MyCustomClass> myMap;
MyCustomClass test1;
MyCustomClass test2;

myMap["hi"] = test1; // adds an element with a key
myMap["hi"] = test2; // replaces

When test2 replaces test1, does test1 get released from memory?

Brother Bob
Brother Bob

The copy of test1 that is stored in the map is destructed, yes. The orignal test1 you made a copy of remains unchanged.

SiCrane
SiCrane

The copy of test1 that is stored in the map is destructed, yes.

Actually, no it's not. The second myMap["hi"] returns a reference to the MyCustomClass object constructed by the first myMap["hi"] call. That reference is used to call the assignment operator. It won't be destroyed until its node is erased, either explicitly through erase() or implicitly such as through the destruction of the map.
Brother Bob
Brother Bob

Correct, I should have realized that if I spent just a few seconds thinking about it; "replaces" as OP wrote in his comment is more accurate. But the key thing, I believe, is what happens to test1: nothing.

Vincent_M
Vincent_M

Once I replace test2 with test1, has this caused a memory leak? I'm wondering if I should be safe, and use insert(), or just check if the key already in use with find(), erase() if valid, then insert() or construct using "[] =" (bracket assignment).

zacaj
zacaj

Since you didn't allocate them using new there won't be a memory leak

Vincent_M
Vincent_M

Ok, that's good to hear. I thought "new" was used internally, and wanted to make sure since the data is copied into meaning more data is allocated upon performing that operation.

alvaro
alvaro
The general idea is that the semantics of the STL are such that things just work. If you don't know all the details of how the STL should be used most effectively, you could end up with slow code, but it shouldn't leak.
Adam_42
Adam_42

You can get leaks if MyCustomClass doesn't follow the rule of three, or simply doesn't have a destructor when it needs one.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.