【 以下文字转载自 JobHunting 讨论区 】
发信人: swanswan (swan), 信区: JobHunting
标 题: 有个SB interviewer和我说++i比i++好
发信站: BBS 未名空间站 (Thu Mar 22 16:09:09 2012, 美东)
他的意思是假设是operator重载
++i先做++再放在stack上,i++则先复制一份copy到stack上再做++,多了一份复制(假
设编译无优化)
大家看有道理吗?
I did a real test on arm compiler turn off optimization:
the O0 code is exactly the same, except that post operator++()(int dummy)
has an extra dummy parameter which is required by c++ to identify the
difference of prefix and postfix.
2nd, even I change the Test& operator++() into Test operator++(), it still generates the same code.
printf("%d \n", 10+ (abc++).value);
sub r3, fp, #8
mov r0, r3
mov r1, #0 --> the dummy parameter of postfix
bl _ZN4TestppEi --> call the overload function
mov r3, r0
ldr r3, [r3, #0]
add r3, r3, #10
ldr r0, .L12
mov r1, r3
bl printf
printf("%d \n", 20+ (++abc).value);
sub r3, fp, #8
mov r0, r3
bl _ZN4TestppEv --> call the overload function
mov r3, r0
ldr r3, [r3, #0]
add r3, r3, #20
ldr r0, .L12
mov r1, r3
bl printf
c++ source code
#include
class Test {
public:
Test(int v):value(v){};
Test():value(0){};
int value;
int operator()();
Test& operator++();
Test& operator++(int postVersion);
};
Test& Test::operator++(){
value++;
return *this;
}
Test& Test::operator++(int postVersion){
value++;
return *this;
}
int Test::operator()() {
return value;
}
int main(int argc, char** argv)
{
Test abc(100);
printf("%d \n", 10+ (abc++).value);
printf("%d \n", 20+ (++abc).value);
}