I’m working on a program that stores a vital data structure as an unstructured string with program-defined delimiters (so we need to walk the string and extract the information we need as we go) and we’d like to convert it to a more structured data type.
In essence, this will require a struct with a field describing what kind of data the struct contains and another field that’s a string with the data itself. The length of the string will always be known at allocation time. We’ve determined through testing that doubling the number of allocations required for each of these data types is an unnacceptable cost. Is there any way to allocate the memory for the struct and the std::string contained in the struct in a single allocation? If we were using cstrings I’d just have a char * in the struct and point it to the end of the struct after allocating a block big enough for the struct and string, but we’d prefer std::string if possible.
Most of my experience is with C, so please forgive any C++ ignorance displayed here.
If you have such rigorous memory needs, then you’re going to have to abandon
std::string.The best alternative is to find or write an implementation of
basic_string_ref(a proposal for the next C++ standard library), which is really just a char* coupled with a size. But it has all of the (non-mutating) functions ofstd::basic_string. Then you use a factory function to allocate the memory you need (your struct size + string data), and then use placement new to initialize thebasic_string_ref.Of course, you’ll also need a custom deletion function, since you can’t just pass the pointer to “delete”.
Given the previously linked to implementation of
basic_string_ref(and its associated typedefs,string_ref), here’s a factory constructor/destructor, for some type T that needs to have a string on it:Obviously, you’ll need to fill in the other constructor parameters yourself. And your type’s constructor will need to take a
string_refthat refers to the string.