Reputation: 3469
For instance I have static declaration of string
std::string s("test");
The memory will be allocated dynamically for the string. When the string s
goes out of scope
the memory allocated for string will be deallocated ?
In case of std::map
std::map <std::string, std::string> testMap;
Similarly if this testMap
also goes out of scope, the destructors of the std::string
are called and string's memory will be deallocated ?
Comments ? Thanks in advance :)
Upvotes: 1
Views: 2827
Reputation: 29450
When using the standard C++ containers, all allocated memory is automatically deallocated. You don't have to worry about doing it yourself.
Upvotes: 2
Reputation: 7119
In addition to answers already posted, I have to notice that std::string
and std::map
(as well as other containers) use allocators for memory management. Particularly this means that after deallocate()
they return memory back to allocator, but not to system directly, and it is allocator (or STL implementation) depended will it be returned to system or not. Because calling system memory management (like malloc()
) could be heavy enough, some allocators do not return memory, so next call to allocate()
will be much faster if some preallocated block exists. Sometimes it may leads to spurious memory leaks detected by various tools.
Upvotes: 1
Reputation: 258548
If you're talking about the dynamic allocation that goes on inside of std::string
, then yes, it will be deallocated automatically.
If you're using new
to allocate the actual std::string
, then you need to use delete
afterwards.
Upvotes: 6