Say I have the following member function:
void CFoo::regWrite( int addr, int data )
{
reg_write( addr, data ); // driver call to e.g. write a firmware register
}
Clearly, calling this function doesn't modify the internal state of the object it is called on. However, it changes the state of whatever this Foo
instance represents.
In circumstances such as these, should Foo::regWrite(int addr, int data)
be a const function?
By Alex Allain. The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).
const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic , meaning the compiler has to respect changes made by other threads.
The const means that the method promises not to alter any members of the class. You'd be able to execute the object's members that are so marked, even if the object itself were marked const : const foobar fb; fb.
In some programming languages, const is a type qualifier (a keyword applied to a data type) that indicates that the data is read-only.
You have to decide what the meaning is of "logically const" for the class CFoo
, and that depends what the class is for.
If CFoo
is construed as referring to some data, then it might make sense to be able to modify that data via a const
instance of CFoo
, in which case your member function would be const
. For examples of this consider other types that refer to some data -- you can modify the referand of a char *const
or a const std::unique_ptr<char>
.
If CFoo
is construed as owning some data, then it might make sense to forbid modification via a const
instance of CFoo
. For examples of this consider containers, where the elements are logically "part of the object's state" even when they aren't physically part of the object. So vector::operator[]
has a const overload that returns a const T&
rather than a T&
, the insert
member function is non-const, etc.
It is up to the programmer to define what 'const' shall mean for a class. With the specifier mutable
you can even have a const
object with changing values in a member. When it comes to hardware one might consider the configuration as the target for const correctness: as long as the configuration does not change the object can be considered constant.
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