User
User

Reputation: 65951

Understanding const_iterator with pointers?

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?

Upvotes: 5

Views: 10227

Answers (3)

Antti Huima
Antti Huima

Reputation: 25522

const_iterator is not about whether you can modify the container or not, but about whether you can modify the objects in the container or not. In your case the container contains pointers, and you cannot modify the pointers themselves (any more than you could modify integers...) You can still make call to non-const Refresh() behind a pointer from the collection, because that call does not change the pointer itself.

Difference between const_iterator and iterator is important [only] when your container contains e.g. class instances, not pointers to them, but the instances themselves, for example in a container

list < pair < int , int > >

If 'it' is a const_iterator into this list, you can't do

it->first = 5

but if it is iterator (not const_iterator), that works.

Upvotes: 2

Seth Carnegie
Seth Carnegie

Reputation: 75130

You're not modifying the contents of the container. The contents of the container are just pointers. However, you can freely modify whatever the pointers point to.

If you didn't want to be able to modify what the pointers point to, you'd need a vector<const Customer*>.

Upvotes: 4

K-ballo
K-ballo

Reputation: 81349

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..;

Upvotes: 10

Related Questions