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");
newallocates memory on the heap, soAllocates a
CStringon the heap and assigns a pointer to it toasdf. That memory will not be freed, nor will the destructor ofasdfbe called until you calldelete asdf.Without
new, you are allocating on the stack, soallocates stack memory, which
asdfrepresents. This memory is automatically reclaimed when the stack is unwound (as in when you return from a function) and the destructor ofasdfis automatically called when it goes out of scope.Also,
CStringcleans up its own resources, so if theCStringobject 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.