c++ stl const iterator and const pointer
-
06-04-2021 - |
Question
I'm a little confuse about meaning of this const keyword I have a class like this
class ClassA {
public:
typedef std::tr1::shared_ptr<ClassA> ptr;
typedef std::tr1::shared_ptr<const ClassA> const_ptr;
void oper() const;
void oper();
private:
.....
};
int main()
{
std::list<ClassA::const_ptr> const_list;
.....
for(std::list<ClassA::const_ptr>::iterator it = const_list.begin();\
it != const_list.end(); it++)
{
(*it)->oper();
}
return 0;
}
I already get const version of oper() from the code above. So I can't imagine what will I get if I change std::list::iterator to std::list::const_iterator.
Solution
Your situation is a bit confusing because there are two levels of indirection (the iterator and the smart pointer), with const
being applicable in some way to any of them (and also to the referenced object).
You can apply const
:
- to the object itself; this means that it cannot be modified;
- to the smart pointer; this means that the smart pointer cannot be modified, e.g. cannot be reseated via
reset
; - in some sense to the iterator, using a
const_iterator
; this means that it will yield aconst
reference to the object it refers (=>the smart pointer) and that it cannot be used to modify the sequence it refers to.
Expanding a little:
Remember that a const shared_ptr<const ClassA>&
(which is what you get by dereferencing a const_iterator
) is different from a shared_ptr<const ClassA>&
(which you get from a normal iterator
): although on both you cannot modify the pointed object (due to the fact that shared_ptr
refers to a const ClassA
), on the const
one you cannot modify the shared_ptr
itself, which e.g. means that you can't reset
it to point to another object, you cannot assign another shared_ptr
to it, ...
Remember also that const
versions of iterators, beside yielding a const
reference to what they refer to, also disallow modifying the container through them (e.g. you cannot erase
an element via a const_iterator
).
OTHER TIPS
Not sure if you understand what void oper() const
in class ClassA
means: In particular, it means that means is that ClassA::oper()
is not allowed to modify any members of ClassA
.
Which has little baring on your choice of iterator or const_iterator, that choice would have different implications.