过去的情况是,预增量是首选,因为类上重载的后增量需要返回表示增量之前对象状态的临时副本。
看来这不再是一个严重的问题(只要内联到位),因为我的旧 C++ 编译器(GCC 4.4.7)似乎将以下两个函数优化为相同的代码:
class Int {
//...
public:
Int (int x = 0);
Int & operator ++ ();
Int operator ++ (int) {
Int x(*this);
++*this;
return x;
}
};
Int & test_pre (Int &a) {
++a;
return a;
}
Int & test_post (Int &a) {
a++;
return a;
}
这两个函数的最终汇编结果是:
.cfi_startproc
.cfi_personality 0x3,__gxx_personality_v0
pushq %rbx
.cfi_def_cfa_offset 16
.cfi_offset 3, -16
movq %rdi, %rbx
call _ZN3IntppEv
movq %rbx, %rax
popq %rbx
.cfi_def_cfa_offset 8
ret
.cfi_endproc
If nothing is inlined, however, there seems to still be a benefit to preferring pre-increment to post-increment, since test_post
is forced to call out into operator++(int)
.
Let's assume operator++(int)
is inlined as an idiomatic copy constructor, call to the pre-increment, and return of the copy, as illustrated above. If the copy constructor is inlined or the default copy constructor implementation, is that sufficient information for the compiler to optimize post-increment so that test_pre
and test_post
become identical functions? If not, what other information is required?