Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const_iterator and const pointer

On page 108 in C++ primer Fifth edition by Lippman et al., it says:

A const_iterator behaves like a const pointer (§ 2.4.2, p. 62). Like a const pointer, a const_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?

like image 732
baimiaomark Avatar asked May 09 '15 03:05

baimiaomark


People also ask

What is a const pointer?

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.

What is a const_iterator?

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.

Is const pointer same as reference?

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.

What is the use of const pointer in C?

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.


2 Answers

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".)

like image 197
jogojapan Avatar answered Sep 25 '22 14:09

jogojapan


When the author said "const pointer" I think he indeed meant "pointer to const".

The reason he probably does it is twofold:

  1. We almost never use a constant pointer (at least not directly - templates don't count).

  2. A pointer to const is written as const T*, which you pronounce as "const pointer".

like image 28
orlp Avatar answered Sep 24 '22 14:09

orlp