1. 为了支持形如“a=b=c”的连锁形式,最好令operator=返回一个reference to *this.

2. 如果类中含有用于指向堆内存的指针,那么赋值操作符就要注意自我赋值的问题,例如:

class A{
public:
    ...
    A& operator=(const A& tmp){
        if (ptr != tmp.ptr){
            delete ptr;
            ptr = new int(*tmp.ptr);
        }
        return *this;
    }
private:
    int* ptr;
};
View Code

相关文章: