简体   繁体   English

重载的前缀/后缀编译器优化

[英]Overloaded Prefix/Postfix Compiler Optimization

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. 例如,在以下代码中,大多数编译器将i++视为++i并生成相同的程序集。

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("*");

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 .) (这被称为“as-if”规则 。)

So yes, in your first snippet ++i and i++ will be optimised to the same thing on most compilers. 所以是的,在你的第一个代码片段中, ++ii++将在大多数编译器上针对相同的事情进行优化。 (Although that was once not the case, which is why old cats like me still use ++i in a for loop.). (虽然曾经不是这种情况,这就是为什么像我这样的老猫仍然在for循环中使用++i 。)

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. 在第二种情况下,编译器可以优化值复制,作为命名返回值优化(NRVO)扩展的一部分,假设未使用返回的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM