简体   繁体   中英

deallocation of memory allocated in std::string in C++

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 :)

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.

When using the standard C+ containers all allocated memory is automatically deallocated. You don;t have to worry about doing it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM