是否有可能从std::string中获取内存(就像string move tor所做的那样)

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

本文关键字:string tor move std 有可能 获取 是否 内存 就像      更新时间:2023-10-16

如果我有我自己的vector<char>版本的内部类(我控制源代码),并且为了示例,我不能将其更改为std::string,是否有方法从std::string窃取内存,就像移动std::string的构造函数一样。

所以像这样:

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

我想我听说过一些未来的建议,将.release()添加到std::stringstd::vector中,但我说的是现在。

No。std::string管理的缓冲区是私有的。您可以通过&str[0]访问它,但string仍然拥有它,并在它超出范围时将其销毁。您无法告诉str它现在拥有一个不同的缓冲区,或者将其底层缓冲区设置为nullptr,或者以任何其他方式使其而不是 delete该缓冲区。

那是std::string的工作。它拥有它的缓冲区,它不会放弃它。