是否有可能从std :: string中获取内存(就像字符串移动ctor那样)? [英] Is it possible to take memory from std::string(like string move ctor does)?

查看:273
本文介绍了是否有可能从std :: string中获取内存(就像字符串移动ctor那样)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的内部类是我自己的vector<char>版本(我控制源代码),并且出于示例的原因,我无法将其更改为std::string,那么有没有办法从std::string窃取内存>,就像std::string的move构造函数一样.

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.

是这样的:

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

我想我听说过将来将.release()添加到std::stringstd::vector的一些建议,但是我在谈论当前时间.

I think I heard of some future proposals to add .release() to std::string or std::vector but I am talking about present time.

推荐答案

否. std::string管理的缓冲区是它专用的.您可以通过&str[0]访问它,但是string仍将拥有它,并在超出范围时将其销毁.您无法告诉str它现在拥有一个不同的缓冲区,也无法将其基础缓冲区设置为nullptr,也无法通过其他任何方法将其设置为 not delete该缓冲区.

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.

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

That's std::string's job. It owns its buffer and it's not going to give it up.

这篇关于是否有可能从std :: string中获取内存(就像字符串移动ctor那样)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆