如何从内存中正确释放 std::string

新手上路,请多包涵

当我完成使用它时,从堆上分配的内存中删除 std::string 的最佳方法是什么?谢谢!

原文由 bbosak 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 4.4k
2 个回答

std::string 只是一个普通的类1 ,所以通常的规则适用。

如果您在堆栈上分配 std::string 对象,作为全局对象,作为类成员,……你不需要做任何特别的事情,当它们超出范围时,它们的析构函数被调用,它会小心自动释放用于字符串的内存。

 int MyUselessFunction()
{
    std::string mystring="Just a string.";
    // ...
    return 42;
    // no need to do anything, mystring goes out of scope and everything is cleaned up automatically
}

唯一需要做的事情是当您使用 new 运算符在堆上分配 std::string 时;在这种情况下,与分配有 new 的任何对象一样,您必须调用 delete 来释放它。

 int MyUselessFunction()
{
    // for some reason you feel the need to allocate that string on the heap
    std::string * mystring= new std::string("Just a string.");
    // ...
    // deallocate it - notice that in the real world you'd use a smart pointer
    delete mystring;
    return 42;
}

正如示例中所暗示的那样,通常在堆上分配 std::string 是没有意义的,并且,当您需要时,您仍然应该将此类指针封装在智能指针中以避免甚至冒内存泄漏的风险(以防万一异常,多个返回路径,…)。


  1. 实际上 std::string 被定义为
   namespace std
   {
       typedef std::basic_string<char> string;
   };

因此,它是 basic_string 类型为 char 的字符的模板类的实例化的同义词(这不会改变答案中的任何内容,但是在 SO 上,即使是新手,您也 必须 是迂腐的问题)。

原文由 Matteo Italia 发布,翻译遵循 CC BY-SA 2.5 许可协议

也许您正在处理真正释放内部字符串缓冲区的问题?

出于性能原因,大多数实现都保留分配的内部缓冲区,即使字符串被“清空”。另外:小字符串(小于 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题