In class we're implementing vector, but I don't understand why the code for the input operator overloading is working:
istream& operator>> (istream& in, const Vector& A)
{
for (int i = 0; i < A.size; i++)
in >> A.data[i];
return in;
}
I tried the code and it worked pretty well, but how can the vector reference be const even though we're inputting values for A?!
Assuming that
Vector
contains someT* data
pointer as a member, aconst Vector
's member would be aT* const
pointer.T* const
is aconst
pointer toT
, thoughT
is mutable.Therefore,
in >> A.data[i];
works, since it simply writes mutable data.If you want constness to propagate deeply to the next pointer, you have to ensure this yourself:
Now,
in >> A.data()[i]
would fail becauseA.data()
would yield a pointer toconst T
.This technique is used by containers like
std::vector
, seestd::vector::data
.Note on language evolution
There is
std::experimental::propagate_const
which solves this without extra manual effort.P2670: Non-transient constexpr allocation proposes a
propconst
specifier which would could be used as follows: