hkBattousai
hkBattousai

Reputation: 10931

Do I need to write the `const` keyword when passing a `const_iterator` as argument?

static void MyClassMethod(
          std::list<AClass>                 & AnObject,
    const std::list<AClass>::const_iterator & BeginningPoint);

In my code, I'm passing a const_iterator of a const STL object. It feels like one of the constantnesses is redundant.

How does it differ if I only remove the const keyword, or if I only change const_iterator to iterator?

Upvotes: 3

Views: 225

Answers (2)

Neil Kirk
Neil Kirk

Reputation: 21773

std::list<AClass>::iterator&

You can change the value through the iterator and you can change what the iterator points to outside the function.

std::list<AClass>::const_iterator&

You can't change the value through the iterator but you can change what the iterator points to outside the function.

const std::list<AClass>::iterator&

You can change the value through the iterator but you can't change what the iterator points to outside the function.

const std::list<AClass>::const_iterator&

You can't change the value through the iterator and you can't change what the iterator points to outside the function.

Take note that the iterators are passed by reference. If they were passed by value, the first const wouldn't matter so much. This is because changing the position of the iterator would only effect your local copy.

Upvotes: 6

Luchian Grigore
Luchian Grigore

Reputation: 258608

A const_iterator means you can't modify the object it "points" to (iterators have pointer semantics). A const const_iterator means you can't modify the iterator itself.

So:

 const std::list<AClass>::const_iterator it = smth;
 it = smthElse;

is illegeal, and

 std::list<AClass>::const_iterator it = smth;
 it->nonConstMethodOfAClass();

is illegal.

Upvotes: 7

Related Questions