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

后端 未结 5 966
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 01:36

    Yes, absolutely.

    Compilers do this all the time, and more.

    For example, if all your function did were return true, and its definition were visible to the compiler at the callsite, the entire function call would probably be elided, resulting in just:

    someObscureFunction(true, true);
    

    A program for which the compiler has sufficient information may be "optimised" from a quite complex chain of tasks down to perhaps one or two instructions. Now, actually operating on member variables is pushing the optimiser to its limit to some degree, but if the variables are private, are given a known initial value, and are not mutated by any other member function, I don't see why a compiler couldn't just inline its known value if it wanted to. Compilers are very, very smart.

    People think that a compiled program is a one-to-one mapping of lines in your source code, but this is almost never true. The entire purpose of C++ is that it is an abstraction of what your computer's actually going to be doing when it runs your program.

提交回复
热议问题