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?
A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.
const can't be optimized because there may be other mutable references to the same memory object.
const member functions Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.
No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With