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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With