c++ - 为什么编译器允许在引用 const 迭代器的函数中发送对迭代器的引用?

标签 c++ visual-studio-2015 const-iterator

我对 const_iterators 有点困惑。例如,让我们考虑以下功能:

void functionForConstIterator(std::list<int> const& list, std::list<int>::const_iterator& const_iter)
{
    const_iter = list.begin();
}

现在我可以写:

void main()
{
    std::list<int> myList = {1, 2, 3, 4, 5};
    std::list<int> const& listRef = myList;
    std::list<int>::iterator iter;

    functionForConstIterator(listRef, iter);
    *iter = 7;

    for (auto it = myList.begin(); it != myList.end(); ++it)
        std::cout << *it << " ";
}

输出是{7, 2, 3, 4, 5}。为什么?如果我在容器上得到一个 const 引用,我不必更改它。这是 Visual Studio 2015 编译器。

最佳答案

If I get a const reference on a container, I should not be able to change it.

没错。但是,您没有在容器上获得 const 引用。尽管它的名字,const_iterator 不是 const从语言的角度。姓名const是向程序员表明您将无法通过此迭代器更改容器。迭代器本身仍然是一个可以更改的公平目标。

此外,迭代器是一个const_iterator仅在函数内部。在函数之外,即在 main 中, 这是一个常规 std::list<int>::iterator ,在调用函数之前和之后保持完全可变。

关于c++ - 为什么编译器允许在引用 const 迭代器的函数中发送对迭代器的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38524974/

相关文章:

c++ - 在 CUDA/Thrust 中,如何在 for-each 操作期间访问 vector 元素的邻居?

c++ - 概率和随机数

c# - 运行代码片段并呈现结果的基本 VS 扩展(类似于 watch )

c++ - 为什么 const_iterator 不像 reverse_iterator 那样提供基类?

c++ - 映射运算符 [] 的编译错误

c++ - 如何在 GCC 主干中使用 <stacktrace>?

xaml - XAML 文件的智能感知 (Xamarin.Forms)

visual-studio - 可以停止由 VIsual Studio 2015 生成 *.ipdb *.iobj 文件吗?

C++ std::vector::const_iterator 问题

c++ - 从 begin() 而不是 cbegin() 获取 const_iterator