Does const vector<A>
mean that its elements are const
as well?
In the code below,
v[0].set (1234);
in void g ( const vector<A> & v )
produces the compiler error
const.cpp:28:3: error: member function 'set' not viable: 'this' argument has type 'const value_type' (aka 'const A'), but function is not marked const
Why?
But (*v[0]).set(1234);
in void h ( const vector<A *> & v )
is OK for the compiler.
What's the difference between the versions?
// ...........................................................
class A {
private:
int a;
public:
A (int a_) : a (a_) { }
int get () const { return a; }
void set (int a_) { a = a_; }
};
// ...........................................................
void g ( const vector<A> & v ) {
cout << v[0].get();
v[0].set (1234);
} // ()
// ...........................................................
void h ( const vector<A *> & v ) {
cout << (*v[0]).get();
(*v[0]).set(1234);
} // ()
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.