经过多年的盲目接受 std::vector<T>::operator[] const
返回 const_reference
,但是,鉴于 const 如何用于智能指针,我现在开始怀疑为什么它和其他 STL 容器是这样设计的。似乎 const std::vector
的“常量”被应用于 vector 及其元素,而对于智能指针,“常量”仅适用于指针而不适用于它指向的元素。
澄清一下,似乎应该有一个类似 vector 的容器,其中 const
只是意味着用户无法更改容器的大小,但容器中的元素是可变的。我的主要问题是:是否有什么东西可以阻止这种类型的容器“const correct”?
似乎有一些通过添加额外的间接层(例如 std::vector<std::unique_ptr<T>> const
)来实现这一点的 hackish 解决方法,但我正在寻找在维护方面不那么尴尬的东西。
顺便说一句,如果在 STL 容器之前将智能指针合并到语言中,const 访问器是否仍会像今天这样定义?
最佳答案
To clarify, it seems like there should be a vector-like container where const just means that a user can't change the size of the container, but the elements in the container are mutable.
那是 std::array
。您在编译时设置大小。为了在构造函数时设置大小,建议使用 dynarray
。
关于c++ - 容器的常量正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622532/