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

bbo*_*sak 42 c++ string

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

Mat*_*lia 70

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
}
Run Code Online (Sandbox Code Playgroud)

您必须执行某些操作的唯一情况是std::string使用new运算符在堆上分配时; 在这种情况下,与分配的任何对象一样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;
}
Run Code Online (Sandbox Code Playgroud)

正如示例中所暗示的那样,一般来说std::string,在堆上分配a是没有意义的,并且,当您需要时,仍然应该将这样的指针封装在智能指针中,以避免内存泄漏的风险(如果是异常,多个返回路径, ...).


  1. 实际上std::string被定义为

    namespace std
    {
        typedef std::basic_string<char> string;
    };
    
    Run Code Online (Sandbox Code Playgroud)

    所以这是对的实例化的代名词basic_string模板类类型的字符char(这不回答任何改变,但这样你就必须是迂腐甚至新手问题).


The*_*uck 8

std::string foo("since it's on the stack, it will auto delete out of scope");
Run Code Online (Sandbox Code Playgroud)

要么:

std::string* foo = new std::string("allocated on the heap needs explicit destruction")
delete foo;
Run Code Online (Sandbox Code Playgroud)