C++ Const Correctness

From Schmid.wiki
Jump to: navigation, search

The general rule for using the const keyword is:

If you can use const, you should use const.

Contents

Value Substitution

Use constants instead of #defines, as constants are type checked:

const int WIDTH = 800;

Preferably define them in classes:

class Thing {
public:
    static const int MAX_SIZE; // access by Thing::MAX_SIZE
};

and set the value in the implementation:

const int Thing::MAX_SIZE = 100;

Safety Constants

When you don't want a variable to change beyond its initialization, make it constant:

const int x = foo.getValue();
// x++;    <- this is illegal

Constant Pointers and Pointer Constants

const int* x;            // a pointer to a constant
int* const x = &y;       // a constant pointer
int const* const x = &y; // a constant pointer to a constant :)

Methods and Functions

Typical usage:

int calculateSomething(const int& x)  // x will not be changed in calculateSomething()
const int* getSomething(void)         // get a pointer to a constant

Concerning constant objects:

class Thing {
public:
    void doSomething(int x) const;    // can be called from a constant object
};
...
const Thing thing;
thing.doSomething(0);

The following means that x won't be changed inside the method. As x is passed-by-value this does not mean anything to a user of the interface.

void doSomething(const int x) { }

Replace by this code, as not to confuse the interface:

void doSomething(int xc) {
    const int& x = xc;
    // use x but don't change it
}
Personal tools