Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does const after a function optimize the program?

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?

like image 702
Unknown Avatar asked May 01 '09 03:05

Unknown


People also ask

What does const do after function?

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.

Does const optimize?

const can't be optimized because there may be other mutable references to the same memory object.

What does making a function const do?

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.

Does const make code faster?

No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.


2 Answers

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.

like image 114
Jim Buck Avatar answered Sep 21 '22 14:09

Jim Buck


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.

like image 31
Charlie Martin Avatar answered Sep 22 '22 14:09

Charlie Martin