Are modern C++ compilers able to avoid calling a const function twice under some conditions?

后端 未结 5 869
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 01:10

For instance, if I have this code:

class SomeDataProcessor
{
public:
    bool calc(const SomeData & d1, const SomeData & d2) const;
private:
    //Some n         


        
5条回答
  •  独厮守ぢ
    2021-02-05 02:01

    No, given the shown code, the compiler cannot guarantee that the proposed optimization will have no observable differences, and no modern compiler will be able to optimize away the second function call.

    A very simple example: this class method might use a random number generator, and save the result in some private buffer, that some other part of the code reads later on. Obviously, eliminating a function call now results in fewer randomly-generated values being placed in that buffer.

    In other words, just because a class method is const does not mean that it has no observable side effects when it's called.

提交回复
热议问题