【问题标题】:overloaded increment's return value重载增量的返回值
【发布时间】:2009-01-21 14:30:14
【问题描述】:

在他的 The C++ Programming Language 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
}

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

谢谢。

【问题讨论】:

  • 应该是:Ptr_to_T& operator--(); // 前缀 Ptr_to_T 运算符--(int); // 后缀

标签: c++ operator-overloading


【解决方案1】:

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

【讨论】:

  • 结合您不能通过引用返回临时的事实,这是一个很好的答案。
【解决方案2】:

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

MyType& operator++()
{
    // do the incrementation
    return *this;
}

由于 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
}

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

C++ Faq Lite 也有一段关于该主题的段落。

【讨论】:

  • 我明白了:CircularInt.cpp:在成员函数'CircularInt& CircularInt::operator++(int)'中:CircularInt.cpp:48:17:警告:对局部变量'result'的引用返回[ -Wreturn-local-addr] CircularInt 结果(*this); // 为结果复制一份
  • @Tomer:您不能返回对局部变量的引用,因为该变量在离开函数时将被销毁,因此调用者最终会得到对不再存在的变量的引用。您需要返回一个值而不是引用。
【解决方案3】:

假设我使用重载的预增量来增加一个私有成员。返回对私有成员的引用不会将 ++private_var 表达式转换为左值,从而可以直接修改私有成员吗?

【讨论】:

  • 你不会返回对私有成员的引用,而是返回你的类对象。 (因为外部世界在增加你的对象,而不是它的私有字段)。
猜你喜欢
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
相关资源
最近更新 更多