Search code examples
c++visual-studio-2015const-iterator

Why compiler allows send a reference to iterator in function which takes a reference to const iterator?


I am a little messed up with const_iterators. For example, let's consider the function:

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

Now I can write:

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 << " ";
}

The output is {7, 2, 3, 4, 5}. Why? If I get a const reference on a container, I have not to change it. This is Visual Studio 2015 compiler.


Solution

  • The Microsoft STL's list::iterator derives from list::const_iterator. This is why you can pass a reference to your iterator to the function expecting a const_iterator without problems.

    The assignment inside the function is thus a slicing assignment, but this has no particular effect in this case, since iterator has no virtual functions and introduces no new members.

    Thus you have stealthily converted a const_iterator to an iterator thanks to the assignment.

    Edit: I have created a Connect issue for this:

    https://connect.microsoft.com/VisualStudio/feedback/details/2962643