Understanding C++ dynamic allocation
Posted
by
kiokko89
on Stack Overflow
See other posts from Stack Overflow
or by kiokko89
Published on 2011-01-10T13:01:19Z
Indexed on
2011/01/10
19:53 UTC
Read the original article
Hit count: 235
Consider the following code:
class CString
{
private:
char* buff;
size_t len;
public:
CString(const char* p):len(0), buff(nullptr)
{
cout << "Constructor called!"<<endl;
if (p!=nullptr)
{
len= strlen(p);
if (len>0)
{
buff= new char[len+1];
strcpy_s(buff, len+1, p);
}
}
}
CString (const CString& s)
{
cout << "Copy constructor called!"<<endl;
len= s.len;
buff= new char[len+1];
strcpy_s(buff, len+1, s.buff);
}
CString& operator = (const CString& rhs)
{
cout << "Assignment operator called!"<<endl;
if (this != &rhs)
{
len= rhs.len;
delete[] buff;
buff= new char[len+1];
strcpy_s(buff, len+1, rhs.buff);
}
return *this;
}
CString operator + (const CString& rhs) const
{
cout << "Addition operator called!"<<endl;
size_t lenght= len+rhs.len+1;
char* tmp = new char[lenght];
strcpy_s(tmp, lenght, buff);
strcat_s(tmp, lenght, rhs.buff);
return CString(tmp);
}
~CString()
{
cout << "Destructor called!"<<endl;
delete[] buff;
}
};
int main()
{
CString s1("Hello");
CString s2("World");
CString s3 = s1+s2;
}
My problem is that I don't know how to delete the memory allocated in the addition operator function(char* tmp = new char[length]
). I couldn't do this in the constructor(I tried delete[] p
) because it is also called from the main function with arrays of chars as parameters which are not allocated on the heap...How can I get around this? (Sorry for my bad English...)
© Stack Overflow or respective owner