Search code examples
c++const-string

const_string as map key; make a buffer copy?


the whole point of const_string is avoiding make a unnecesary copy when the string is not supposed to change.

However, there are circumstances where you cannot guarantee the lifetime of the const char* source to outlive the const_string, for instance, if using const_string as keys of the map, if some of the const char* become reclaimed, you'll have very amusing segmentation faults to debug ahead of you.

Is there a way to tell const_string, hey pal, please keep a private copy of this const char*? or std::string?

I'll refer to a previous question so you understand what i'm after.


Solution

  • And what doesn't work? By looking at the code (the documentation is mediocre at best), I can see that const_string(charp) (as opposed to const_string(boost::cref(charp)) with charp being char* should make a copy of the data. Another possibility is using the const_string(Iterator begin, Iterator end) constructor. (See the two-argument constructor of const_string_storage in storage.hpp, line 153)

    They even use a temporary std::basic_string to initialize const_string in their test (I haven't run it to be honest), so it should work normally.