menu

hjk41的日志

Avatar

More Effecitve C++ 6: Distinguish between postfix and prefix forms of increment and decrement

What's the difference between obj++ and ++obj?


class A{
public:
...
    inline A & operator ++ (){
        *this+=1;
        return *this;
    }

    inline const A operator ++(int){
        A oldVal=*this;
        ++(*this);
        return oldVal;
    }

    A & operator +=(const A & a){...}
};

A a;
++a;    // calls   A & operator ++ ()
a++;    // calls   const A operator ++(int)

1. Why does the postfix increment operator have to take an argument?
That's just to distinguish postfix increment operators from prefix ones.

2. As we can see, the postfix operator has to construct a temporary object which makes it slower than the prefix one. So we should use the prefix increment operators on user-defined classes whenever possible.

3. Why return a const object?
That's because C++ don't allow operations like:


int i=0;
i++++;


So we have to follow it, and forbid something like obj++++. A simple way to do this is to have the postfix operator return a const object.

评论已关闭