Search code examples
c++iteratormove-semantics

Iterator validity following a std::move of pointed element


I wasn't able to find anything in the standard regarding this, is this UB or well defined behaviour?

// Assuming T supports move semantics
void sink(T&& t) 
{
    // bla bla
}

std::list<T> list = getSomeList();

for (auto it = list.begin(); it != list.end(); )
{
    if (some pred) 
    {
        sink(std::move(*it));
        it = list.erase(it) // is this valid following the std::move() ??
    }
    else
        ++it;
}

Solution

  • Moving from - or more generally: making any changes to - a pointed element has no effect on the iterator. It will remain valid.

    P.S. your example doesn't actually move from the element. It only binds an rvalue reference to it.