Search code examples
c++visual-c++mfccstring

Need to delete CString after use to free memory?


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 the new 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"); 

Solution

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