C++赋值函数一些考虑

来源:互联网 发布:淘宝banner图 编辑:程序博客网 时间:2024/06/06 08:34
// Primary programmer use this wayCMyString & 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 wayCMyString & 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;}

0 0
原创粉丝点击