Understanding const_iterator with pointers?

User picture User · Nov 5, 2011 · Viewed 9.4k times · Source

I'm trying to understand what const_iterator means. I have the following example code:

void CustomerService::RefreshCustomers()
{
    for(std::vector<Customer*>::const_iterator it = customers_.begin();
        it != customers_.end() ; it ++)
    {
        (*it)->Refresh();
    }
}

Refresh() is a method in the Customer class and it is not defined as const. At first thought I thought const_iterator was supposed to disallow modification to the elements of the container. However, this code compiles without complaint. Is this because there's an extra level of indirection going on? What exactly does const_iterator do/mean?

UPDATE

And in a situation like this, is it best practice to use const_iterator?

Answer

K-ballo picture K-ballo · Nov 5, 2011

A const_iterator over a vector<Customer*> will give you a Customer * const not a Customer const*. So you cannot actually change the value being iterated (a pointer), but you sure can change the object pointed to by it. Basically all it says in your case is that you can't do this:

*it = ..something..;