如何从内存中正确释放std :: string [英] How to properly free a std::string from memory

查看:2082
本文介绍了如何从内存中正确释放std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果您分配 std :: string 对象在堆栈上,作为全局变量,作为类成员,...你不需要做任何特殊的,当他们走出范围,它们的析构函数被调用,它会自动释放用于字符串的内存。 / p>

If you allocate std::string objects 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.

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 才能释放它。 >

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

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 ,当你需要的时候,你仍然应该将这样的指针封装在智能指针中,以避免内存泄漏的危险(在异常情况下,多个返回路径,...)。

As implied in the example, in general it's pointless to allocate a std::string on 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, ...).


  1. 其实 std :: string 定义为

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

因此它是实例化 basic_string char 的字符的模板类(这不会更改答案中的任何内容,但是您必须甚至在新手上问题)。

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

这篇关于如何从内存中正确释放std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆