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

杀马特。学长 韩版系。学妹 提交于 2019-12-22 04:09:26

问题


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:


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.



来源:https://stackoverflow.com/questions/24658341/using-a-custom-allocator-in-stdstring-to-re-use-an-already-allocated-char-buff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!