Search code examples
c++stliteratorswap

Incremented iterator std::next when swapping


Consider the code:

list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(++i));

Why does the swap do nothing? While the following works as expected?

list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(next(i)));

Solution

  • In the first code, the order of evaluation of the two ops *i and *(++i) unspecified after c++17, hence the second one may execute before the first, and then the swapping swaps two equivalent values.

    In the attached link, u can see that

    f(++i, ++i); // undefined behavior until C++17, unspecified after C++17

    But in the second code you have different parameters and std::next() returns a new iterator.