3

Is compiler allowed to optimize an overloaded postfix operator and replace it with prefix operator? (provided that compiler knows what overloaded function does)

For example, in the following code, most compilers treat i++ as ++i and generate same assembly.

for(int i=0; i<5; i++)
    printf("*");

Then, could same apply for the following code?

class Integer {
    int data;
    Integer& operator++() { ++data; return *this; }
    Integer operator++(int) { Integer ret = *(this); ++(*this); return ret; }
    // And more overloads...
};

for(Integer i=0; i<5; i++)
    printf("*");
quartzsaber
  • 174
  • 3
  • 10

1 Answers1

4

An optimiser is allowed to do anything so long as it doesn't change the behaviour of the code. (This known as the "as-if" rule.)

So yes, in your first snippet ++i and i++ will be optimised to the same thing on most compilers. (Although that was once not the case, which is why old cats like me still use ++i in a forloop.).

In your second case, the compiler could optimise away the value copy as part of an extension of named return value optimisation (NRVO), assuming the returned result is not used.

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483