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
Vectorcontains someT* datapointer as a member, aconst Vector's member would be aT* constpointer.T* constis aconstpointer toT, thoughTis 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_constwhich solves this without extra manual effort.P2670: Non-transient constexpr allocation proposes a
propconstspecifier which would could be used as follows: