If I want to cast to const std::vecor<cosnt int>
, how should I do that? I've tried const_cast
but doesn't work
Short answer: Don't.
When you make a std::vector<int>
const, as-in const std::vector<int>
, the contents themselves become implicitly const
as well. In other words, if you write something like this, you won't be able to modify the elements:
const std::vector<int> values{1,2,3,4,5};
//Nope
//values.emplace_back(6);
//Also Nope
//values[3] = 5;
//Still nope
//values.erase(values.begin() + 1, values.begin() + 3);
//Nuh-uh
//std::vector<int> & mutable_values = values;
//This, however, is okay.
std::vector<int> const& immutable_values = values;
//Same restrictions though
//immutable_values[2] = 6;
//immutable_values.emplace_back(7);
//This is fine
std::vector<int> copy_of_values = values;
//But that's because you made a copy
copy_of_values.emplace_back(6);
assert(copy_of_values.size() != values.size());
assert(copy_of_values != values);
This is why STL containers like std::vector
, std::list
, std::map
, and so on, prohibit the use of const
members within their template parameter lists: because making the container itself const
also makes its contents const
, which is a stated contract of the design of these containers. Some "containers" don't have this property, like Smart Pointers, which is why you'll sometimes see stuff like this:
std::shared_ptr<int> ptr = std::make_shared<int>(42);
std::shared_ptr<const int> non_modifying_ptr = ptr;
Which is part of the core functionality of reference-counted pointers.
This, incidentally, is all part of making sure your code is "const-correct", and I strongly advise you do a google search on that very subject and learn about what it is, and how to properly apply it in your code to make your code safer and more performant.