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.
No. The buffer that
std::string
manages is private to it. You can access it via&str[0]
, but thestring
will still own it and will destroy it when it goes out of scope. You have no way of tellingstr
that it now owns a different buffer, or to set its underlying buffer tonullptr
, or any other way of making it notdelete
that buffer.That's
std::string
's job. It owns its buffer and it's not going to give it up.