Explore which is more efficient: ++ I or I ++

  • 2020-04-02 01:41:36
  • OfStack

The answer:

There is no difference in efficiency with built-in data types;

In the case of custom data types, ++ I is more efficient!

Analysis:

(in the case of custom data types)

++ I returns a reference to the object;

I++ always creates a temporary object, destroys it when the function exits, and calls the copy constructor when the value of the temporary object is returned.

(overloads the two operators as follows)


#include <iostream>
using namespace std;
class MyInterger{
public:
    long m_data;
public:
    MyInterger(long data):m_data(data){}
    MyInterger & operator++(){
        cout<<"Integer::operator++() called!"<<endl; 
        m_data++;
        return *this;
    }
    MyInterger operator++(int){
        cout<<"Integer::operator++(int) called!"<<endl;
        MyInterger tmp = *this;
        m_data++;
        return tmp;
    }
};
int main()
{
    MyInterger a = 1;
    a++;
    ++a;
    return 0;
}


Related articles: