簡體   English   中英

C ++ postfix ++運算符重載

[英]C++ postfix ++ operator overloading

根據這個: 運算符重載

class X {
  X& operator++()
  {
    // do actual increment
    return *this;
  }
  X operator++(int)
  {
    X tmp(*this);
    operator++();
    return tmp;
  }
};

是實現++運算符的方法。 第二個(后綴運算符)按值返回,而不是按引用返回。 這很清楚,因為我們無法返回對本地對象的引用。 因此,我們不是在堆棧上創建tmp對象,而是在堆上創建它並返回對它的引用。 所以我們可以避免額外的副本。 所以我的問題是,以下是否有任何問題:

class X {
  X& operator++()
  {
    // do actual increment
    return *this;
  }
  X& operator++(int)
  {
    X* tmp = new X(*this);
    operator++();
    return *tmp;
  }
};

調用者現在必須處理刪除內存。

如果您的目的是避免額外的副本,請記住可能沒有額外的副本。 RVO將避免它 - 返回值將直接放入調用者的變量X中,從而優化副本。

因此,我們不是在堆棧上創建tmp對象,而是在堆上創建它並返回對它的引用。 所以我們可以避免額外的副本。

根據RVO,在大多數情況下沒有額外的副本。 operator++內部的值x直接向上移動為返回值。 檢查一下:

#include <iostream>

class X 
{
    public:

        X() {}
        X( const X & x ) {
            std::cout << "copy" << std::endl;
        }

        X& operator++()
        {
            // do actual increment
            return *this;
        }
        X& operator++(int)
        {
            X x;
            operator++();
            return x;
        }
};

int main()
{
    X x;
    x++;

    return 0;
}

沒有副本(僅通過vc7測試)。 但是,您的實現會在此行中復制:

X tmp(*this);

或者在這個:

X* tmp = new X(*this);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM