先贴出一段代码:

 

class T{
public:
T(){};
T(
const T& t){
if(this==&t){
cout
<<"they are the same!"<<endl;
}
else{
cout
<<"they are different"<<endl;
}
}
T
& operator =(const T& t){
if(this==&t){
cout
<<"they are the same"<<endl;
return *this;
}
else{
cout
<<"they are different"<<endl;
return *this;
}
}
};
int main(){
T a;
a
=a;
}

代码中的拷贝构造函数永远不会出现they are the same,因为不会出现下面这种代码:
T a;
T a(a);//变量a被重定义
而在T& operator=(const T& t)
由于可通出现:
T a;
a=a;
因此,会出现they are the same
对代码的自我赋值的检测可以很好的用于代码的优化中。
Exceptional C++给出了两条规则:
1.对字符串常量指针进行比较的操作是未定义的。编译器可以在重叠的内存区域中存储字符串,从而对内存空间进行优化。因此,我们全完有可能有一个指针指向两个不同的字符串,而如果对指针进行比较的话,那么结果就是相等的。
2.用<,<=,>,>=来对任意的裸指针进行比较,得到的结果往往是未知的。
posted on 2008-12-04 11:40  CUCmehp(likesmiles)  阅读(170)  评论(0编辑  收藏  举报