Рассмотрим следующий код:Понимание C++ динамическое распределение
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;
}
Моя проблема заключается в том, что я не знаю, как удалить память, выделенную в функции оператора сложения (char* tmp = new char[length]
). Я не мог сделать это в конструкторе (я пробовал delete[] p
), потому что он также вызывается из основной функции с массивами символов в качестве параметров, которые не выделяются в куче ... Как я могу обойти это?
Вы также должны работать над оператором присваивания (его небезопасно (предпочитают Copy and Swap Idium)). Смотри ниже. –