[英]Extract const char from std::string without copying?
I was wondering if there is some way to tell the std::string
to release the char*
it is using. 我想知道是否有某种方法告诉std::string
释放它正在使用的char*
。
I imagine that somewhere on the std::string
it has a field of type char*
, I was wanting some method that would to something like that: 我想在std::string
某个地方它有一个char*
类型的字段,我想要一些类似的方法:
const char* std::string::release() {
const char* result = __str;
__size = 0;
__capacity = INITIAL_CAPACITY_WHATEVER;
__str = new char[INITIAL_CAPACITY_WHATEVER];
return result;
}
Not that copying the content is a problem or will affect my performance, I just was felling uncomfortable with wasting time copying something that I am just going to delete after. 不是复制内容是一个问题,或者会影响我的表现,我只是在浪费时间复制我刚刚要删除的东西时感到不舒服。
If you're using C++11, you can use std::move
to move the contents of one string object to another string object. 如果您使用的是C ++ 11,则可以使用std::move
将一个字符串对象的内容移动到另一个字符串对象。 This avoids the overhead of copying. 这避免了复制的开销。
std::string s1 = "hello";
std::string s2(std::move(s1));
However, you cannot directly disassociate the internal char*
buffer from an instance of std::string
. 但是,您无法直接取消内部char*
缓冲区与std::string
实例的关联。 The std::string
object owns the internal char*
buffer, and will attempt to deallocate it when the destructor is invoked. std::string
对象拥有内部char*
缓冲区,并在调用析构函数时尝试释放它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.