当我完成使用它时,从堆上分配的内存中删除 std::string 的最佳方法是什么?谢谢!
原文由 bbosak 发布,翻译遵循 CC BY-SA 4.0 许可协议
当我完成使用它时,从堆上分配的内存中删除 std::string 的最佳方法是什么?谢谢!
原文由 bbosak 发布,翻译遵循 CC BY-SA 4.0 许可协议
也许您正在处理真正释放内部字符串缓冲区的问题?
出于性能原因,大多数实现都保留分配的内部缓冲区,即使字符串被“清空”。另外:小字符串(小于 sizeof(ptr)
)直接存储在保存指针的区域中。这些字节在字符串的生命周期内永远无法回收。
释放内部:经典技巧是在一个范围内使用 swap
。 This force buffer to be really freed (Works also with vector
/ map
/ ostream
/ stringstream
etc …):
string s; // size==0 and capacity==15 as the default proxy of the container (help perf on small string)
s = "Looooooooooooooooooooooooooooooong String"; // size==41 and capacity==47 bytes allocated
s.clear(); // size==0 BUT capacity==47 bytes STILL allocated!!
s = "Looooooooooooooooooooooooooooooong String"; // size==41 and capacity reuse 47 bytes still allocated.
s.resize(0); // size==0 BUT capacity==47 bytes STILL allocated!!
// swap with scope to force freeing string internals
{
string o;
o.swap(s);
} // size==0 AND capacity==15 (back to smallest footprint possible)
s = "12345"; // size==5 AND capacity==15 (the string is IN the container, no new alloc)
原文由 Gordon88 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答2.7k 阅读✓ 已解决
std::string
只是一个普通的类1 ,所以通常的规则适用。如果您在堆栈上分配
std::string
对象,作为全局对象,作为类成员,……你不需要做任何特别的事情,当它们超出范围时,它们的析构函数被调用,它会小心自动释放用于字符串的内存。唯一需要做的事情是当您使用
new
运算符在堆上分配std::string
时;在这种情况下,与分配有new
的任何对象一样,您必须调用delete
来释放它。正如示例中所暗示的那样,通常在堆上分配
std::string
是没有意义的,并且,当您需要时,您仍然应该将此类指针封装在智能指针中以避免甚至冒内存泄漏的风险(以防万一异常,多个返回路径,…)。std::string
被定义为因此,它是
basic_string
类型为char
的字符的模板类的实例化的同义词(这不会改变答案中的任何内容,但是在 SO 上,即使是新手,您也 必须 是迂腐的问题)。