Question

I've seen some methods like this:

void SomeClass::someMethod() const;

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

Edit

I see that the first part of this question has been asked before... BUT, it still doesn't answer the second part: how would this optimize the program?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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];

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top