为什么在C++ 11中允许通过const_iterator进行擦除?

j_h*_*j_h 3 c++ stl const delete-operator c++11

从GCC 4.9.2开始,现在可以编译通过const_iterator插入或删除容器元素的C++ 11代码.

我可以看到插入接受const_iterator是多么有意义,但我很难理解为什么允许通过const_iterator进行擦除是有意义的.

此问题已在前面讨论过,但我没有看到行为改变背后的基本原理的解释.

我能想到的最好的答案是,改变的目的是使const_iterator的行为类似于const T*的行为.

显然允许使用const T*删除的一个主要原因是启用声明,例如:

const T* x = new T;
....
delete x;
Run Code Online (Sandbox Code Playgroud)

但是,它还允许以下不太理想的行为:

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
Run Code Online (Sandbox Code Playgroud)

而且我很难理解为什么const_iterator模仿这种行为是件好事.

Ben*_*igt 8

erase并且insertconst该集合的非成员函数.非const成员函数是公开变异操作的正确方法.

论证的常数是无关紧要的; 它们不被用来修改任何东西.可以修改集合,const因为集合是非集合(保存在隐藏this参数中).

相比:

template <typename T>
std::vector<T>::iterator std::vector<T>::erase( std::vector<T>::const_iterator pos );
                                                                ^^^^^ ok
Run Code Online (Sandbox Code Playgroud)

到一个不允许的类似重载

template <typename T>
std::vector<T>::iterator std::vector<T>::erase( std::vector<T>::iterator pos ) const;
                                                                         wrong ^^^^^
Run Code Online (Sandbox Code Playgroud)