Does C++11 allow vector<const T>?

Viewed 17869

Container requirements have changed from C++03 to C++11. While C++03 had blanket requirements (e.g. copy constructibility and assignability for vector), C++11 defines fine-grained requirements on each container operation (section 23.2).

As a result, you can e.g. store a type that is copy-constructible but not assignable - such as a structure with a const member - in a vector as long as you only perform certain operations that do not require assignment (construction and push_back are such operations; insert is not).

What I'm wondering is: does this mean the standard now allows vector<const T>? I don't see any reason it shouldn't - const T, just like a structure with a const member, is a type that is copy constructible but not assignable - but I may have missed something.

(Part of what makes me think I may have missed something, is that gcc trunk crashes and burns if you try to instantiate vector<const T>, but it's fine with vector<T> where T has a const member).

5 Answers

Even though we already have very good answers on this, I decided to contribute with a more practical answer to show what can and what cannot be done.

So this doesn't work:

vector<const T> vec; 

Just read the other answers to understand why. And, as you may have guessed, this won't work either:

vector<const shared_ptr<T>> vec;

T is no longer const, but vector is holding shared_ptrs, not Ts.

On the other hand, this does work:

vector<const T *> vec;
vector<T const *> vec;  // the same as above

But in this case, const is the object being pointed to, not the pointer itself (which is what the vector stores). This would be equivalent to:

vector<shared_ptr<const T>> vec;

Which is fine.

But if we put const at the end of the expression, it now turns the pointer into a const, so the following won't compile:

vector<T * const> vec;

A bit confusing, I agree, but you get used to it.

To my best knowledge, if you want each T element in your vector is const, just use const vector instead. Because if your vector is const-qualified, only the const-qualified methods that won't modify any T element can be called.

Related