How to properly free a std::string from memory
c++, string
Solution
`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, ...).
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).
Problem
What's the best way to delete an std::string from memory allocated on the heap when I'm done using it? Thanks!