++i和i++的效率孰优孰劣

在内建数据类型的情况下,效率没有区别;

在自定义数据类型的情况下,++i效率更高!

分析:

(自定义数据类型的情况下)

++i返回对象的引用;

i++总是要创建一个临时对象,在退出函数时还要销毁它,而且返回临时对象的值时还会调用其拷贝构造函数。

(重载这两个运算符如下)

class Integer{

public:

    Integer(long data):m_data(data){}

    Integer& operator++(){//前置版本,返回引用

        cout<<” Integer::operator++() called!”<

        m_data++;

        return *this;

    }

    Integer operator++(int){//后置版本,返回对象的值

cout<<” Integer::operator++(int) called!”<

Integer temp = *this;

m_data++;

return temp;//返回this对象的旧值

    }

private:

    long m_data;

};

void main(void)

{

    Integer x = 1;//call Integer(long)

    ++x;//call operator++()

    x++;//call operator++(int)

}

原文地址:https://www.cnblogs.com/xiemingjun/p/9633647.html