Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom allocator in std::string to re-use an already allocated char buffer

I need to use an already allocated char* buffer (with the string content) in a std::string object. After some research I found that this is almost impossible and std::string would have its own private copy of data always. The only remaining way I can think of to 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 should only use the allocator to allocate memory to hold its string data and for nothing else. Is this the case?

like image 514
user3612009 Avatar asked Jul 09 '14 15:07

user3612009


1 Answers

std::string is a typedef of basic_string that already explicitly uses the default allocator. There is no way for std::string to use a different allocator. Even if you created a new typedef of basic_string with the allocator you wanted, it couldn't be passed to an API expecting a std::string.

Unfortunately I can't see any way to meet all the needs you've specified in any of the current C++ standards, unless you're able to somehow relax one or more of your requirements.

One possible creative solution, if you're able to do so, would be to allocate your "orignal" char* buffer as a std::string, utilizing resize. Then you could swap that string into your new one to make it take ownership.

like image 91
Mark B Avatar answered Oct 24 '22 08:10

Mark B