在google C++编程规范中有下面一段描述:
仅在代码中需要拷贝一个类对象的时候使用拷贝构造函数;不需要拷贝时应使用
DISALLOW_COPY_AND_ASSIGN。
定义:通过拷贝新建对象时可使用拷贝构造函数(特别是对象的传值时)。
优点:拷贝构造函数使得拷贝对象更加容易,STL容器要求所有内容可拷贝、可赋值。
缺点:C++中对象的隐式拷贝是导致很多性能问题和bugs的根源。拷贝构造函数降低了
代码可读性,相比按引用传递,跟踪按值传递的对象更加困难,对象修改的地方变得难以捉
摸。
而具体的则没有明说,今天看了《More Effective C++》之后,重新思考了这个问题。
禁用复制构造函数的原因有下面两个(包括但不限于 :)):
#ifndef _HUMAN_H
#define _HUMAN_H
#include
class Human {
public :
Human &operator=(const Human &rhs){
printf("Human &operator=(const Human &rhs)\n");
return *this;
}
};
class Male : public Human{
public :
Male &operator= (const Human &rhs) {
printf("Male &operator= (const Human &rhs)\n");
return *this;
}
Male &operator=(const Male &rhs) {
printf("Male &operator=(const Male &rhs)\n");
return *this;
}
};
class Female : public Human {
public :
Female &operator= (const Human &rhs) {
printf("Female &operator= (const Human &rhs)\n");
return *this;
}
Female &operator=(const Female &rhs) {
printf("Female &operator=(const Female &rhs)\n");
return *this;
}
};
#endif // _HUMAN_H
int main() {
Human *male1 = new Male();
Human *male2 = new Female();
*male1 = *male2;
return 0;
}
class NoCopyAndAssign {
public :
NoCopyAnd *clone() const = 0;
private :
NoCopyAndAssign(const NoCopyAndAssign &);
void operator=(const NoCopyAndAssign &);
};