11

Consider the following program:

struct list_wrapper
{
    std::vector<int>    m_list;
};

int main()
{
    std::vector<int> myList { 1, 1, 2, 3, 5 };

    const std::vector<int>::iterator iter = myList.begin();

    list_wrapper wrappedList;
    wrappedList.m_list = std::move(myList);

    // Can I still dereference iter?

    return 0;
}

After the call to std::move(myList), does iter now point to a valid item inside wrappedList.m_list, or do move constructors/assignments invalidate all iterators?

Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65
  • 1
    `std::move` does nothing on its own. The move assignment definitely invalidates iterators on both sides, though. – user2357112 Dec 29 '16 at 17:56
  • maybe this QA will help: http://stackoverflow.com/questions/3413470/what-is-stdmove-and-when-should-it-be-used?rq=1 – Francis Cugler Dec 29 '16 at 17:57
  • @user2357112 [actually...](http://eel.is/c++draft/container.requirements.general#12) (the relevant paragraph is identical in n3337, just at [container.requirements.general]/11 instead of 12.) – jaggedSpire Dec 29 '16 at 17:57

2 Answers2

7

After http://en.cppreference.com notes (emphasis mine):

After container move assignment (overload (2)), unless elementwise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in *this. The current standard makes this guarantee via the blanket statement in §23.2.1[container.requirements.general]/12, and a more direct guarantee is under consideration via LWG 2321

Notes

As hvd have rightly pointed out there is at least once case where the move assignent is forced to invalidate iterators - when the new container has incompatible allocator.

As Ben Voigt noted there is a broader discussion in this topic over here and it actually already covers the c++11 aspects of the question...

Community
  • 1
  • 1
W.F.
  • 13,888
  • 2
  • 34
  • 81
  • 4
    That's the right bolding for the OP's code, but for the general question also note also the "unless elementwise move assignment is forced by incompatible allocators": there are cases where iterators are invalidated by move assignment. –  Dec 29 '16 at 18:04
  • 1
    Can you add this answer to http://stackoverflow.com/questions/11021764/does-moving-a-vector-invalidate-iterators?rq=1 please – Ben Voigt Dec 29 '16 at 18:16
0

No, they should not get invalidated after a move operation.

23.3.6.5/1

all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)

Wagner Patriota
  • 5,494
  • 26
  • 49