How to properly free a std::string from memory

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


Solution 1:

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

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
}

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;
}

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. Actually std::string is defined as

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

    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).

Solution 2:

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;

Solution 3:

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

Solution 4:

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;
}