const vector implies const elements?

The first version

v[0].set (1234); 

does not compile because it tries to change the vector's first element returned to it by reference. The compiler thinks it's a change because set(int) is not marked const.

The second version, on the other hand, only reads from the vector

(*v[0]).set(1234);

and calls set on the result of the dereference of a constant reference to a pointer that it gets back.

When you call v[0] on a const vector, you get back a const reference to A. When element type is a pointer, calling set on it is OK. You could change the second example to

v[0]->set(1234);

and get the same result as before. This is because you get a reference to a pointer that is constant, but the item pointed to by that pointer is not constant.


So a const object can only call const methods. That is:

class V {
  public:
    void foo() { ... }        // Can't be called
    void bar() const  { ... } // Can be called
};

So let's look at a vector's operator[]:

reference       operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;

So when the vector object is const, it will return a const_reference.

About: (*v[0]).set(1234);

Let's break this down:

A * const & ptr = v[0];
A & val = *ptr;
val.set(1234);

Note that you have a constant pointer to variable data. So you can't change what is pointed at, but you can change the value that the pointer points at.


Yes, a const vector provides access to its elements as if they were const, that is, it only gives you const references. In your second function, it's not the objects of type A that are const, but pointers to them. A pointer being const does not mean that the object the pointer is pointing to is const. To declare a pointer-to-const, use the type A const *.

Tags:

C++

Constants