C++对象的拷贝与赋值操作

About... 李先静

This author published 367 posts in this site.

Share

FacebookTwitterEmailWindows LiveTechnoratiDeliciousDiggStumbleponMyspaceLikedin

Comments


E
March 26th, 2009

恩,不过个人觉得对于新人,这个概念是那么的诱人,但是副作用又是那么的明显。

而你作为leader,能做的就是明确告诉他们可不可以用,以及为什么。

个人建议是完全不用,C++的class不像C的struct那么单纯,所以拷贝构造和赋值本身都是很容易造成隐含BUG的因素。
至于原因,参看symbian~那样一个完全C++的系统,从CBase开始就禁用了所有的拷贝构造及赋值~


qb_2008
March 28th, 2009

拷贝构造函数最好在遇到自身时把内部指针设为NULL,防止指针指错地址。
CString::CString(const CString& other)
{
if(this == &other)
{
printf(“CString::CString(const CString& other)\n”);
m_pszBuffer=NULL;
return;
}

printf(“CString::CString(const CString& other)\n”);
m_pszBuffer=other.m_pszBuffer!=NULL?strdup(other.m_pszBuffer) : NULL;
}


admin
March 29th, 2009

printf(”CString::CString(const CString& other)\n”);
m_pszBuffer=NULL;

这样处理存在问题吧。

Leave a comment