Is it possible to take memory from std::string(like string move ctor does)?

岁酱吖の 提交于 2020-01-03 09:16:17

问题


If I have my internal class that is my own version of vector<char> (I control the source) and for the sake of example I can not change it to be std::string is there a way to steal memory from std::string, just like move constructor of std::string does.

So something like this:

std::string str{"abcdefghijklmnopqrstu"};
MyVectorCharClass mvc(std::move(str)); // Constructor takes memory from str

I think I heard of some future proposals to add .release() to std::string or std::vector but I am talking about present time.


回答1:


No. The buffer that std::string manages is private to it. You can access it via &str[0], but the string will still own it and will destroy it when it goes out of scope. You have no way of telling str that it now owns a different buffer, or to set its underlying buffer to nullptr, or any other way of making it not delete that buffer.

That's std::string's job. It owns its buffer and it's not going to give it up.



来源:https://stackoverflow.com/questions/31767209/is-it-possible-to-take-memory-from-stdstringlike-string-move-ctor-does

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