重载增量的返回值

jac*_*hab 3 c++ operator-overloading

在他的C++编程语言中,Stroustrup为inc/dec重载提供了以下示例:

class Ptr_to_T {
    T* p;
    T* array ;
    int size;
public:
    Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p
    Ptr_to_T(T* p); // bind to single object, initial value p
    Ptr_to_T& operator++(); // prefix
    Ptr_to_T operator++(int); // postfix
    Ptr_to_T& operator--(); // prefix
    Ptr_to_T operator--(int); // postfix
    T&operator*() ; // prefix
}
Run Code Online (Sandbox Code Playgroud)

为什么前缀运算符通过引用返回,而后缀运算符按值返回?

谢谢.

Tim*_*sch 17

后缀运算符在递增之前返回值的副本,因此它几乎必须返回临时值.前缀运算符确实返回对象的当前值,因此它可以返回对其当前值的引用.


Luc*_*lle 8

为了更好地理解,您必须想象(或看看)这些运算符是如何实现的.通常,前缀运算符++将或多或少地写为:

MyType& operator++()
{
    // do the incrementation
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

由于this已经"就地"修改,我们可以返回对实例的引用,以避免无用的副本.

现在,这是后缀运算符++的代码:

MyType operator++(int)
{
    MyType tmp(*this); // create a copy of 'this'
    ++(*this); // use the prefix operator to perform the increment
    return tmp; // return the temporary
}
Run Code Online (Sandbox Code Playgroud)

由于后缀运算符返回临时值,它必须按值返回(否则,您将获得悬空引用).

C++ FAQ精简版也有关于这个问题的一个段落.