I'm currently working on a device with very little memory (4MB) and I have a component of my program that requires an std::set. I would like to migrate this set from using std::string to using const char pointers but I was wondering how memory is allocated to constant character pointers when used in a std::set.
Will the memory allocated for each entry to the std::set be freed when the pointer is removed from the set (by using .clear() or going out of scope), or will the string literal remain in memory until the end of the program's execution?
Thank you very much for your help. :)
The STL containers always calk the default destructors for elements they contain when they are cleaned up. For a set holding raw ‘char *‘ pointers, this will do nothing and the memory will be leaked. You are responsible for cleaning ip this sort of memory yourself.
For this reason, it's generally considered bad practice to store raw pointers in STL containers.
If you really must use an STL set with raw C strings in it, that's fine, but do be aware that you'll have to reclaim the memory yourself. You will also need to provide a custom comparator to the set so that e stored strings are compared by value rather than by pointer (the default ordering on ‘char *‘s just compares the pointers, not the strings).