I have a question regarding when to use delete to free memory used by a pointer. I have a class function that uses dynamically allocated memory and I want to properly use delete to free up the space when I am done with it.
// Overloaded addition operator.
CSimpleString operator+(const CSimpleString& aSimpleString) const
{
// Unsinged int variable that represents the length of both strings added together.
size_t len = m_Length + aSimpleString.m_Length + 1;
// Pointer to char.
char* cstr = 0;
// Allocate space for both strings + \0.
cstr = new char [len+1];
// String to hold left operand.
string s1 = (pmessage);
// String to hold right operand.
string s2 = (aSimpleString.pmessage);
// String to add both of them together.
string s3;
// Append both strings to s3.
s3.append(s1);
s3.append(s2);
// Safe copy std::string to const char*
strcpy_s (cstr, len +1, s3.c_str());
return CSimpleString(cstr);
}
I just need to know where to place the delete statement and why I need to place it there.
Should it be in the class function before the return statement? In the class function after the return statement? Or in the main function? And where-ever I place it, why is that place the correct place?
The book I"m reading from doesn't really explain the correct placement of the delete statement. It would seem that I would need to use the delete statement in the class function because the dynamically allocated variable is local to the function but if I place it after the return statement will it still be executed?
Thank You.