Wednesday, May 20, 2009

A pointer to something that needs to be constant.

I've seen this code before...

type *getNodeList() const;

The problem with it is that it should not compile. The reason?
The "const" at the end of the method prototype says that you wont change *this. However, you are giving no guarantee that you'll keep this promise because you are returning type *.

For all the compiler knows, you're going to be an evil person and use the pointer to change *this. However, some compilers give you the benefit of the doubt and will happily compile this for you.

Thankfully, gcc is not one of them. For this to compile you have to ensure that you won't change *this. To guarantee this you need to make the pointer a constant type, type const * (I like this method of placing const to the right of the type but const type * means the same thing so it's no big deal.)

Therefore you get.

type const *getNodeList() const;

This should compile because you now have enough guaratees in place that the compiler will trust you. Of course you can override this type of behavor but I don't recommend it.