2011-02-12 125 views
29

当我完成使用后,从堆中分配的内存中删除std :: string的最佳方法是什么?谢谢!如何从内存中正确释放std :: string

+0

与其他任何对象一样。真的,你能澄清你的问题吗?你在做什么,你想要达到什么目标,你尝试了什么,以及它如何工作? – 2011-02-12 18:08:57

+0

你能扩展你的问题吗?在什么情况下? – vz0 2011-02-12 18:09:40

回答

52

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

如果您将作为全局变量的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类型的角色的实例化的同义词(这不回答任何改变,但在你的必须甚至在新手问题上迂腐)。

4

如果它在堆上,则使用delete,如果它位于堆栈上,则不使用delete

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

或:

std::string* foo = new std::string("allocated on the heap needs explicit destruction") 
delete foo; 
1
void foo() { 
    string* myString = new string("heap-allocated objects are deleted on 'delete myString;'"); 
    cout << *myString << endl; 
    delete myString; 
} 

或更好,但避免可能的指针和时使用自动变量:

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

只是治疗的std :: string任何基本类型。

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