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

标签 c++ c++11 stl constants delete-operator

从 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 模仿这种行为是一件好事。

最佳答案

eraseinsert 是集合的非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/

相关文章:

c++ - 是否有标准库函数可以反转 STL 堆栈?

c++ - 在二进制字符串的数字之间留出空间

c++ - 有没有办法使dlopen故意失败

c++ - rand() 函数的动态链接器错误

c++ - 使用字符串和流头文件和函数将 c++ 代码转换为 arduino

c++ - 很难理解 std::basic_string 内存分配

c++ - 这是向容器添加元素的正确方法吗?

c++ - 使用Crypto++生成指定范围内的随机数

c++ - 与一般的 makefile 作斗争

c++ - 模板函数错误, "no matching function for call to..."