On page 108 in C++ primer Fifth edition by Lippman et al., it says:
A
const_iterator
behaves like aconst
pointer (§ 2.4.2, p. 62). Like aconst
pointer, aconst_iterator
may read but not write the element it denotes; [...]
I understand the function of const_iterator
, but is this comparison correct? I think its behavior is more like "pointer to const
".
Did I misunderstand something?
A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.
A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value ( const T& ) and prevents modification of the referenced value: it enforces const -correctness.
Const pointers can be NULL. A reference does not have its own address whereas a pointer does. The address of a reference is the actual object's address. A pointer has its own address and it holds as its value the address of the value it points to.
Constant pointers: In constant pointers, the pointer points to a fixed memory location, and the value at that location can be changed because it is a variable, but the pointer will always point to the same location because it is made constant here.
You are right. The authors explicitly refer to section 2.4.2 of their book (I have just updated your question to reflect this), where they define how they intend to use the terminology "const pointer" vs. "pointer to const". Given this precise definition, they should have said "pointer to const" in the section you quoted from.
(However, other authors in other contexts use the terminology less precisely, and outside this context, I would not find it unusual if somebody referred to "pointer to const" as "const pointer".)
When the author said "const pointer" I think he indeed meant "pointer to const".
The reason he probably does it is twofold:
We almost never use a constant pointer (at least not directly - templates don't count).
A pointer to const is written as const T*
, which you pronounce as "const pointer".
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