It used to be the case that pre-increment would be preferred because an overloaded post-increment on a class necessitated the return of a temporary copy that represented the state of the object before the increment.
It seems this is no longer a serious concern (so long as inlining is in place), since my old C++ compiler (GCC 4.4.7) seems to optimize the following two functions down into identical code:
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;
}
The resulting assembly for both functions is:
.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 intooperator++(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?