前置++为什么比后置++效率高

本文详细解析了C++中前置与后置递增运算符的实现方式及其区别。通过具体示例代码说明了这两种运算符如何工作,以及它们在实际应用中的效率考量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是一个简单的例子模拟分析++源码:

class  CInt  { 
    private : 
      int  m_value; 
} ; 
CInt  &  CInt:: operator ++ ( )  //  前置的是没有参数的,并且返回引用 
   { 
    this -> m_value += 1 ; 
    return   *   this ; 
} 
const  CInt CInt::opeartor ++ (Int)  //  后置的有一个匿名参数,并且返回const值 
   { 
   Const old  =   * this ; 
    ++ ( * this ); 
    return  old; 
}

前置仅仅是对自身进行运算,并将自身返回,这样外面可以直接对这个返回对象再进行操作 ,如(++it)->function()。
后置因其返回的不是原来的对象,此时再进行额外操作,改变的是临时对象的状态。

‘++i’ is equivalent to: ‘i=i+1; /* then use ‘i’ as the ‘i’ in your expression. */’

‘i++’ is equivalent to: ‘int tmp = i; i=i+1; /* then use ‘tmp’ as ‘i’ in your expression. */’

so ‘++i’ is a bit more efficient than ‘i++’. however, if you just write a stand-along ‘i++’ or ‘++i’, the temporary object ‘tmp’ is unnecessary, so any compiler should be able to completely optimize that way, making ‘i++’ is equally efficient as ‘++i’.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值