// Primary programmer use this way
CMyString & CMyString::operator=(const CMyString & str)
{
if(this == &str)
return *this;
delete [] m_pData;
m_pData = NULL;
/*
* Here may be failed. If this step failed, and next step will
* failed too. And the pointer m_pData will not point to the
* original space it will point to NULL. It's so easily lead to crashes.
*/
m_pData = new char[strlen(str.m_pData) + 1];
strcpy(m_pData, str.m_pData);
return *this;
}
// The better way
CMyString & CMyString::operator=(const CMyString & str)
{
if(this != &str)
{
/*
* strTemp is local variable just in scope of "if", so when
* program run out of the scope of "if", strTemp will call
* destructor free the area that strTemp.m_pData point at.
*/
CMyString strTemp(str);
char *strTemp = strTemp.m_pData;
/*
* so the memory where m_pData point at will been free
* by strTemp.m_pData with program run out of the scope
* of "if"
*/
strTemp.m_pData = m_pData;
m_pData = pTemp;
}
return *this;
}
C++赋值函数一些考虑
最新推荐文章于 2023-03-26 17:07:09 发布