Is it possible to take memory from std::string(lik

2019-06-19 02:47发布

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条回答
倾城 Initia
2楼-- · 2019-06-19 03:07

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.

查看更多
登录 后发表回答