10
votes

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?

1
There's been proposals for string_view or string_ref that offer the std::string interface, without owning the underlying buffer. There are also libraries out there that have their own versions of such a class. Google those terms and you might something that fits your needs. - Praetorian
good info! Will have a look. But for this particular case I will have to stick with std::string as this is part of an API. Thank you for the information. - user3612009

1 Answers

8
votes

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.