I have following code (only relevant portions shown for sake of brevity – please let me know if I have been too brief):
class my_class
{
public:
my_class() {m_i=0;}
set(int i) {m_i = i;}
private:
int m_i;
}
void CallMod()
{
// create a bunch of my_class* o = new my_class() and store in vector<my_class*>
// vObject (left out for brevity)
Mod(vObject);
// will vObject contain pointers to objects that have m_i == 2
}
void Mod(vector<my_class*> const & vObject)
{
BOOST_FOREACH(my_class o, vObject)
{
o->set(2);
}
}
Does this mean that while vObject is const, the modification done by the call to o->set(2) will be retained once Mod returns? Does that indicate that the “const” qualifier will not allow modify operations on vObject (i.e. the vector) but allows modification on the contained pointers to my_class?
Did I understand this right? Any duplicate questions that answers this – I couldn’t find one – links most appreciated.
The vector will be const. You can only get const_iterators from it. You can’t modify it or it’s elements.
The elements in the container will be const pointers. Unfortunately, a const pointer doesn’t mean the element it points to is const, just that the value of the pointer can’t change.
If you had a
vector<my_class>instead ofvector<my_class*>, you would not be able to modify the my_class objects inside the const vector (except if you casted away the const-ness, obviously).