I have this obsession with making things const that really should be const, even when it seems a bit painful to do so.
In this case, I want a vector<int> into which I can add elements, but whose existing elements I cannot change. The problem is that vector<const int> is not allowed.
The purpose is not only to prevent the users of my classes to modify things they shouldn’t modify (this can be easily done by const iterators in member functions). It is also, just as importantly, so I myself don’t later do things in my own code that I didn’t intend on doing.
I have found two alternatives:
-
Use
deque<const int>instead. -
Create my own vector class that wraps the actual
vector, like this (I do this forinthere, but in reality I would use templates for generality)class my_vector { private: std::vector<int> vec; public: std::vector<int>::const_iterator cbegin() { return vec.cbegin(); } std::vector<int>::const_iterator cend() { return vec.cend(); } void push_back(int i) { vec.push_back(i); } };
Which of these ideas (or others) would you recommend? Will the compiler turn the second alternative into code that is just as fast as using the vector directly?
Your obsession is understandable and I do not disagree, but unless you have a really pressing need for it, the effort required might not be worth the effort.
Assuming you chose
vectoras your container based on your design requirement, I would not recommend changing it todeque, or any other type. It would only serve to confuse a future reader (which would likely be yourself), and is also a bad practice otherwise.If we go with your wrapper solution, you would have to
hideoverride all members which could modify the vector, which is a problem since there are a number of methods used to both access and modify, such asoperator[],at(),front(),back(). This could confuse a future reader, since they are used to the “standard”vectorbehavior.By the way, are you sure
deque<const int> foo;works? I get the following error:Edit It seems I didn’t quite answer your question. If you have to pick one, I would choose the wrapper approach.