入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

C++赋值函数一些考虑

创建时间:2016-08-29 投稿人: 浏览次数:366
// 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;
}

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。