在std :: string中使用自定义分配器重新使用已分配的char缓冲区 [英] Using a custom allocator in std::string to re-use an already allocated char buffer
问题描述
我需要在std :: string对象中使用已经分配的char *缓冲区(带有字符串内容).经过一番研究,我发现这几乎是不可能的,并且std :: string总是具有自己的数据私有副本.我能想到的唯一剩下的方法是使用自定义分配器,该分配器将返回已分配的char缓冲区的地址.为此,std :: string应该仅使用分配器分配内存来保存其字符串数据,而别无其他.是这样吗
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
是basic_string
的typedef,已经已明确使用默认分配器. std::string
无法使用其他分配器.即使使用所需的分配器创建了basic_string
的新typedef,也无法将其传递给期望std::string
的API.
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
.
不幸的是,除非您能够以某种方式放宽一个或多个要求,否则我看不到任何方法可以满足您在任何当前C ++标准中指定的所有需求.
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.
如果可能的话,一种可能的创造性解决方案是利用resize
将原始" char*
缓冲区分配为std::string
.然后,您可以将该字符串swap
放入新字符串中,以取得所有权.
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.
这篇关于在std :: string中使用自定义分配器重新使用已分配的char缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!