从 GCC 4.9.2 开始,现在可以编译通过 const_iterator 插入或删除容器元素的 C++11 代码。
我明白插入接受 const_iterator 是多么有意义,但我很难理解为什么通过 const_iterator 允许删除是有意义的。
这个问题已经discussed previously ,但我还没有看到对行为变化背后的基本原理的解释。
我能想到的最佳答案是更改的目的是使 const_iterator 的行为类似于 const T* 的行为。
很明显,允许使用 const T* 删除的一个主要原因是启用如下声明:
const T* x = new T;
....
delete x;
但是,它也允许以下不太理想的行为:
int** x = new int*[2];
x[0] = new int[2];
const int* y = x[0];
delete[] y; // deletes x[0] via a pointer-to-const
我正在努力了解为什么 const_iterator 模仿这种行为是一件好事。
最佳答案
erase
和insert
是集合的非const
成员函数。非常量成员函数是公开变异操作的正确方法。
参数的常量无关紧要;他们没有被用来修改任何东西。可以修改集合,因为集合是非const
(保存在隐藏的this
参数中)。
比较:
template <typename T>
std::vector<T>::iterator std::vector<T>::erase( std::vector<T>::const_iterator pos );
^^^^^ ok
类似的不允许的重载
template <typename T>
std::vector<T>::iterator std::vector<T>::erase( std::vector<T>::iterator pos ) const;
wrong ^^^^^
关于c++ - 为什么在 C++11 中允许通过 const_iterator 进行删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30901105/