Need to delete CString after use to free memory?
Solution 1
new
allocates memory on the heap, so
CString *asdf = new CString("ASDF");
Allocates a CString
on the heap and assigns a pointer to it to asdf
. That memory will not be freed, nor will the destructor of asdf
be called until you call delete asdf
.
Without new
, you are allocating on the stack, so
CString asdf("ASDF");
allocates stack memory, which asdf
represents. This memory is automatically reclaimed when the stack is unwound (as in when you return from a function) and the destructor of asdf
is automatically called when it goes out of scope.
Also, CString
cleans up its own resources, so if the CString
object is cleaned up (goes out of scope if it's on the stack or is deleted if it's on the heap), the resources it uses will also be cleaned up.
Solution 2
CString
manages the memory for the string characters itself, so it will take care of freeing such memory at its destructor (its a bit smarter, but think of it that way).
If you allocate a CString
with new
and never call delete
on it not only are you leaking the memory for the CString
object, but also its destructor is never called so you leak the memory for the string characters as well.
Solution 3
When you create a CString object in most cases you'll end up with two allocations, one for the object itself and one for the characters of the string. The character allocation is hidden within the object and you don't have to worry about it. If you declare the object as an automatic variable as in your first example, the object will be deallocated at the end of the block i.e. the closing brace. If you allocate it with new
you must later delete
it or there will be a memory leak.
Chris Dargis
Updated on June 06, 2022Comments
-
Chris Dargis almost 2 years
If I am using a CString like this:
void myFunc(char *str) { CString s(str); // Manipulate other data with CString // ... // Finished // Should I somehow delete 's' here to avoid a memory leak? }
Is the string erased once the function goes out of scope?
Also, I know that the
new
keyword allocates memory, if I construct an object without thenew
keyword, is memory still allocated? My intuition tells me yes, but I would like to verify.e.g.
CString *asdf = new CString("ASDF"); // same as? CString asdf("ASDF");