Const for containers

After years of blindly accepting the fact that std::vector<T>::operator[] const returns a const_reference , but, in the light of how const works for smart pointers, I am now starting to wonder why this and the rest of the STL containers were designed this way. It seems that "constness" a const std::vector applies to both the vector and its elements, whereas for smart pointers, the "constant" applies only to the pointer, not to the element that it points to.

To clarify, there seems to be a vector container where const means that the user cannot resize the container, but the elements in the container are mutable. My main question is: is there anything that would prevent this type of container from being "const correct"?

There seems to be some hacky workarounds, adding an extra layer of indirection (like std::vector<std::unique_ptr<T>> const ) to accomplish this, but I'm looking for something a little less inconvenient in terms of maintenance.

As a third-party, if smart pointers were included in the language in front of STL containers, would accessory constants still be defined as they are today?

+5
source share
1 answer

To clarify, there seems to be a vector container in which const means that the user cannot resize the container, but the elements in the container are mutable.

This is std::array . You set the size at compile time. To set the size at the time of the constructor, dynarray .

0
source

Source: https://habr.com/ru/post/1239938/


All Articles