Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
NoSenseEtAl Avatar asked Aug 01 '15 23:08

NoSenseEtAl


1 Answers

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.

like image 69
Barry Avatar answered Sep 27 '22 21:09

Barry