Click here to Skip to main content
15,900,906 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using Maps new is called but no delete is caught..Can anyone explain why is that?? NOt calling erase() causes memory leak or the memory is automatically freed when it goes out of scope.
Posted
Updated 19-Feb-12 3:46am
v3

Maps use raii tecnique to avoid resource leak. The map never keeps the handle passed to it but insread it uses copy constructor for allocation so that it can independently delete to ensure raii. This is one reason autoptr cant be used with maps.
 
Share this answer
 
Comments
JackDingler 20-Feb-12 13:35pm    
Right, but you should be safe with shared_ptr.
STL maps will often allocate a larger chunk of memory and use placement-new to construct contained objects in that memory. Unused memory is then usually kept around and re-used the next time you do an insert. The memory is deleted when the map goes out of scope.

Note that you can supply your own "allocator" template argument class to std::map if you want to study how the map allocates and frees memory.
 
Share this answer
 
That means even if i dont call erase after insert the memory will be freed automatically as soon as map gets out of scope?
 
Share this answer
 
Comments
Rahul Rajat Singh 19-Feb-12 23:54pm    
Yes

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900