I know this issue has been discussed several times , but I could not find a post which explains why a copy needs to be made in case of a post-increment operation.
Quoting from a stackoverflow reply:
int j = i++; // j will contain i, i will be incremented.
int j = ++i; // i will be incremented, and j will contain i+1.
Which perfectly makes sense when the definition of post/pre increment is considered. Many times when comparing the performance of pre/post increment it is said that post increment needs to make a copy, increment it and return the copy while pre-increment just increases value and does not create a copy.
Although performance has been compared in tens of posts, I really could not find any explanation on why a copy has to be made in the case of post-increment. Why doesn't it return the old value and then increments the value of the variable by one(or however way operator is overloaded), rather than creating a new object and return that one.
Why doesn't it return the old value and then increments the value of the variable by one
How do you increment the value if you already returned from the function? – Cornetcyint j = i; ++i
, so there is really no temporary (still the compiler complies perfectly with the as-if rule). But there are cases when it's not that easy, especially on types with non-trivial constructors, or think of barriers/memory model which may disallow such a liberal instruction reordering. – Fadein