How does const after a function optimize the program?

前端 未结 6 1919
星月不相逢
星月不相逢 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 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.

提交回复
热议问题