What\'s the best way to delete an std::string from memory allocated on the heap when I\'m done using it? Thanks!
You can treat std::string
like any other class. Use new
for allocation, and delete
once you're done with it.
With C++11, I do not recommend usage of new
and delete
in most cases. If you need to allocate the string on heap, use std::shared_ptr to wrap it:
std::shared_ptr my_string = std::make_shared(std::string("My string"));
As soon as all the copies of my_string
go out of scope, the associated memory is going to be deleted automatically.