作者adrianshum (Alien)
看板Programming
标题Re: [请益] for回圈 i++ or ++i ?
时间Mon Dec 10 22:33:29 2007
※ 引述《solonchuang (企鹅宝宝)》之铭言:
: ※ 引述《adrianshum (Alien)》之铭言:
: : 原因大概因为 i++ 看起来比较顺眼,
: : 还有其实写了很久程式的人也不太会留意
: : 这个分别而已
: : Alien
: 毕竟用了非常久的i++,
: 追根究底请教一下, 为什麽 ++i 比较好?
由於 postfix ++ (或 --) return 的值是
increment/decrement 前的值。假设现在用的
是一个 class 而非一般的 integer:
class MyClass {
public:
MyClass& operator++(); // prefix increment
MyClass operator++(int); // postfix increment
private:
int value;
}
MyClass& MyClass::operator++() {
++this.value;
return *this;
}
MyClass MyClass::operator++(int) {
MyClass tempData;
tempData.value = this.value;
++this.value;
return tempData;
}
由於性质上的差异,postfix ++/-- 无可避免要
一个 temp variable 来作为 return value.
本身的额外memory usage, copy construction etc
都是带来额外负担的部份。
Alien
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 203.218.221.132
1F:→ james732:请问C语言也会存在这样的差异吗? 59.104.63.223 12/10 22:36
2F:推 sunneo:会220.132.228.138 12/10 22:39
3F:推 solonchuang:谢谢你. 123.195.42.87 12/10 22:47
4F:→ adrianshum:像前面有人提过,一般compiler会最佳化203.218.221.132 12/10 22:49
5F:→ adrianshum:基於 C 没有 operator overloading,203.218.221.132 12/10 22:50
6F:→ adrianshum:pre/postfix incr 的分别就不太大了.203.218.221.132 12/10 22:50
7F:推 FlyinDeath:楼上专业~ 61.231.196.82 12/11 11:42
8F:推 GreatShot:++this->value; 220.133.110.47 12/14 02:17