Item 7. Const Pointers and Pointers to Const

In casual conversation, C++ programmers will often say “const pointer” when they really mean “pointer to const.” That’s unfortunate, because these are two different concepts.

T *pt = new T; // ptr to Tconst T *pct = pt; // ptr to const TT *const cpt = pt; // const ptr to T

Before you start tossing const qualifiers into your pointer declarations, you first have to decide what it is that you want to be const: the pointer, the object to which you’re pointing, or both. In the declaration of pct, the pointer is not const, but the object it points to is considered to be const; that is, the const qualifier modifies the T base type, not the * pointer modifier. In the case of cpt, we’re declaring a constant ...

Get C++ Common Knowledge: Essential Intermediate Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.