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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4979681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:04:13  来源:igfitidea点击:

How to properly free a std::string from memory

c++string

提问by bbosak

What's the best way to delete an std::string from memory allocated on the heap when I'm done using it? Thanks!

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

回答by Matteo Italia

std::stringis just a normal class1, so the usual rules apply.

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

If you allocate std::stringobjects on the stack, as globals, as class members, ... you don't need to do anything special, when they go out of scope their destructor is called, and it takes care of freeing the memory used for the string automatically.

如果你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
}

The only case where you have to do something is when you allocate an std::stringon the heap using the newoperator; in that case, as with any object allocated with new, you have to call deleteto free it.

您必须做某事的唯一情况是当您std::string使用new运算符在堆上分配 an时;在这种情况下,与使用 分配的任何对象一样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;
}

As implied in the example, in general it's pointless to allocate a std::stringon the heap, and, when you need that, still you should encapsulate such pointer in a smart pointer to avoid even risking memory leaks (in case of exceptions, multiple return paths, ...).

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



  1. Actually std::stringis defined as

    namespace std
    {
        typedef std::basic_string<char> string;
    };
    

    so it's a synonym for the instantiation of the basic_stringtemplate class for characters of type char(this doesn't change anything in the answer, but on SO you mustbe pedantic even on newbie questions).

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

    namespace std
    {
        typedef std::basic_string<char> string;
    };
    

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

回答by The Communist Duck

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

or:

或者:

std::string* foo = new std::string("allocated on the heap needs explicit destruction")
delete foo;

回答by Oliver Charlesworth

Use deleteif it's on the heap, and nothing at all if it's on the stack.

delete如果它在堆上就使用,如果它在堆栈上则什么都不用。

回答by Lie Ryan

void foo() {
    string* myString = new string("heap-allocated objects are deleted on 'delete myString;'");
    cout << *myString << endl;
    delete myString;
}

or better yet, avoid pointers when possible and use automatic variables:

或者更好的是,尽可能避免使用指针并使用自动变量:

void foo() {
    string myString("stack-allocated string is automatically deleted when myString goes out of scope");
    cout << myString << endl;
}

回答by yu quan

just treat std::string as any basic type.

只需将 std::string 视为任何基本类型。

std::string *str = new std::string("whatever");
///code
delete str;

回答by yu quan

You can treat std::stringlike any other class. Use newfor allocation, and deleteonce you're done with it. With C++11, I do not recommend usage of newand deletein most cases. If you need to allocate the string on heap, use std::shared_ptr to wrap it:

你可以std::string像对待任何其他班级一样对待。使用new用于分配,并且delete一旦你用它做。对于 C++11,我不建议在大多数情况下使用newdelete。如果需要在堆上分配字符串,请使用 std::shared_ptr 包装它:

std::shared_ptr<std::string> my_string = std::make_shared<std::string>(std::string("My string"));

As soon as all the copies of my_stringgo out of scope, the associated memory is going to be deleted automatically.

一旦所有的副本my_string都超出范围,相关的内存将被自动删除。