Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to delete an static std::map?

Tags:

c++

stl

stdmap

In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted.

Thanks.

like image 943
Killrazor Avatar asked Apr 22 '26 10:04

Killrazor


1 Answers

If the map contains pointers that were allocated with new (or new[], or malloc), then each pointer needs a corresponding delete (or delete[], or free).

The map's destructor wont know what to do with a bald pointer. Consider using a smart pointer that has appropriate move semantics like a boost smart pointer or if you've got a very new compiler, one of the C++0x smart pointers. However, do not use the current standard's std::auto_ptr, inside of STL containers. See this thread for why.

Edit:

As Billy ONeal pointed out, boost::ptr_map is also designed exactly for this purpose.

like image 67
luke Avatar answered Apr 23 '26 23:04

luke