menu

hjk41的日志

Avatar

Effective C++ Note 17: Check for assignment to self in operator=

Consider the following code:

String a;
String & b=a;
a=b;


This seems silly, but it is totally legal, and if you don't take it seriously, it can bite you really hard.
Here is an illustration:

class String{
public:
    ...
    String & operator =(const String & rhs){
        delete [] data;
        length=rhs.length;
        data=new char[length+1];
        strcpy(data,rhs.data);
        return *this;
    }
private:
    int length;
    char * data;
};

int main(){
    ....
    String a="Hello";
    a=a;
}


When we run delete[] data, the memory occupied by a.data is freed, so when we run strcpy(data,rhs.data), the result is undefined.
Another reason for us to check for assignment to self is efficiency, for we can return right away if we can detect that it is an assignment to self.

Our problem, then, is how to find if we are assigning to self. There are two ways to do this. We can use the operator== to check if *this==rhs, or we can check if they are pointing to the same object by using this==&rhs. The second one is usually more effective, and thus is more frequently used.
Here comes the right version of operator= for String:

String & String::operator =(const String & rhs){
    if(this==&rhs)
        return *this;
    delete [] data;
    length=rhs.length;
    data=new char[length+1];
    strcpy(data,rhs.data);
    return *this;
}

评论已关闭