Using a Constant Character Pointer in a std::set Container: Memory Consumption

437 views Asked by At

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

2

There are 2 answers

2
templatetypedef On BEST ANSWER

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

1
Oliver Charlesworth On

In short, nothing special will happen.

Deleting a structure that contains a pointer to some memory will only free the memory used by the pointer itself; it will not cause anything to happen to the pointed-to memory.

Unless, of course, you explicitly call free/delete on it. Which is not a good idea in the case of string literals!