How does const after a function optimize the program?

前端 未结 6 1912
星月不相逢
星月不相逢 2021-01-31 05:29

I\'ve seen some methods like this:

void SomeClass::someMethod() const;

What does this const declaration do, and how can it help optimize a prog

相关标签:
6条回答
  • 2021-01-31 05:42

    It tells the compiler that the method has no effect on the classes state; you can't assign to anything in it. Have a look at the C++ FAQ Lite 18.10.

    0 讨论(0)
  • 2021-01-31 05:52

    It prevents someMethod from altering any member variable of an object of that class.

    0 讨论(0)
  • 2021-01-31 06:00

    If the compiler knows that the fields of a class instance are not modified across a const member function call, it doesn't have to reload any fields that it may have kept in registers before the const function call.

    This is sort of referred to the in C++ FAQ in the discussion on const_cast.

    0 讨论(0)
  • 2021-01-31 06:01

    The asm code that is generated for the const method will be the same if the const is there or not. const is a function of the compiler not the runtime, so if there are any performance gains I would think that the compilers optimizer might use the const as a hint for things like inlining or determining side effects for a possible optimization. So in short the optimizer might be able to help out a bit, but if the method is straight forward to begin with then I doubt that the code generated from the optimizer would be any different const or no const.

    Here's an easy optimization I use (rather than hit and miss things like const) which take a second but pay off. Organize your class variables so that they fall on cache line boundaries a little better, and put your most accessed variables together. To do it just put your ints, doubles, floats, etc. together at the top of your class variable declarations and your odd sized variables at the bottom like so:

    int foo; 
    int bar;
    double baz;
    SomeObject obj;
    char ch[14];
    
    0 讨论(0)
  • 2021-01-31 06:03

    It allows you to call the class member function on const objects:

    class SomeClass
    {
    public:
        void foo();
        void bar() const;
    }
    
    SomeClass a;
    const SomeClass b;
    
    a.foo();  // ok
    a.bar();  // ok
    b.foo();  // ERROR -- foo() is not const
    b.bar();  // ok -- bar() is const
    

    There's also the volatile qualifier for use with volatile objects, and you can also make functions const volatile for use on const volatile objects, but those two are exceedingly rare.

    0 讨论(0)
  • 2021-01-31 06:04

    My first thought regarding optimization is that since the 'const' indicates that the instance's state hasn't changed, the compiler possibly has more freedom with respect to reordering nearby calls to methods on that instance.

    0 讨论(0)
提交回复
热议问题