gpt4 book ai didi

c++ - 是否可以从 std::string 中获取内存(就像 string move ctor 那样)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:40 26 4
gpt4 key购买 nike

如果我的内部类是我自己的 vector<char> 版本(我控制来源)并且为了举例,我不能将其更改为 std::string有没有办法从 std::string 窃取内存, 就像 std::string 的 move 构造函数一样做。

所以像这样:

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

我想我听说过一些 future 的建议,以添加 .release()std::stringstd::vector但我说的是现在。

最佳答案

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

那是 std::string 的工作。它拥有自己的缓冲区并且不会放弃它。

关于c++ - 是否可以从 std::string 中获取内存(就像 string move ctor 那样)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31767209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com