menu

hjk41的日志

Avatar

Effective C++ Note 23: Don't try to return a reference when you must return an object

Consider operator+ which always return an object.

class C{
    C operator + (const C & rhs){
        C retval;
        [i]put the result in retval[/i]
        return retval;
    };
};

What if we return a reference?

class C{
    C  & operator + (const C & rhs){
        C retval;
        [i]put the result in retval[/i]
        return retval;
    };
};

C a,b;
C r=a+b;


The result is undefined. retval is a local variable, it goes out of scope as soon as the function operator+ ends. So before we try to assign the return value to r, retval has gone out of scope, thus the reference to it is dirty, thus the result of this operation is undefined.

What about returning a pointer?

class C{
    C  * operator + (const C & rhs){
        C * retval=new retval;
        [i]put the result in retval[/i]
        return retval;
    };
};

C a,b;
C *r=a+b;


Then we have convince the clients of the class C to delete the result so that memory leak won't happen. It is hard, isn't it? And there is still another problem, you can never do such things like r=a+b+c with this operator+.

评论已关闭