Using a custom allocator in std :: string to reuse an already allocated char buffer

I need to use the char * buffer already allocated (with the contents of the string) in the std :: string object. After some research, I found this to be almost impossible, and std :: string will always have its own personal copy of the data. The only remaining way I can do this is to use a custom allocator that will return the address of the already allocated char buffer. For this to work, std :: string must use a allocator to allocate memory to store its string data and for nothing else. This is true?

+8
c ++ memory-management stdstring
source share
1 answer

std::string is a typedef of basic_string that already explicitly uses the default allocator. There is no way to use std::string another dispenser. Even if you created a new typedef from basic_string with the basic_string you need, it cannot be passed to the API waiting for std::string .

Unfortunately, I see no way to satisfy all the needs that you have indicated in any of the existing C ++ standards, if you cannot somehow remove one or more of your requirements.

One possible creative solution, if you are able to do this, would be to assign the "orignal" char* buffer as std::string using resize . Then you can swap enter this line in your new one so that it becomes the owner.

+8
source share

All Articles