About Me

My photo
I'm a colonist who has declared war on machines and intend to conquer them some day. You'll often find me deep in the trenches fighting off bugs and ugly defects in code. When I'm not tappity-tapping at my WMD (also, known as keyboard), you'll find me chatting with friends, reading comics or playing a PC game.

Saturday, May 10, 2008

const_iterator : Safety or Necessity?

(Reader Level : Beginner)
(Knowledge assumptions : const-correctness, std::vector, iterators)

A while back I asked a senior programmer a very naive but valid doubt.
"Are const iterators used only to enforce safety or are there cases where they could be absolutely necessary?"
In reply, this is what I got and the answer was clear.

#include <iostream>
#include <vector>

class A
std::vector<int> _vector;

void Init()
_vector.push_back( 1 );
_vector.push_back( 2 );
_vector.push_back( 3 );

void Display() const
for(std::vector<int>::const_iterator itr = _vector.begin(); itr != _vector.end(); ++itr)
std::cout << (*itr) << std::endl;

int main(int argc, char *argv[])
A a;


return 0;

If we were to try replacing the const_iterator in the Display() function with a normal iterator, the code would simply not compile. This is because the Display() routine is itself const and hence, we must guarantee that no member functions are altered within it. A normal iterator cannot give such a guarantee but a const_iterator can.

No comments: