Validity of pointers to internal data structure when reallocating a std::vector object

后端 未结 3 1598
北荒
北荒 2021-02-19 08:25

Assume there is a class A that contains a vector of ints. Now assume that a vector of A\'s is created. If a reallocation of an A object occurs (so the vector object is moved) du

3条回答
  •  北海茫月
    2021-02-19 08:37

    Your A elements will be moved where possible, and A has an implicit move constructor and implicit move assignment operator, so the member vector will also be moved.

    Now, moving a vector is not necessarily equivalent to a.swap(b), so you cannot rely on the implicit move functions if you want a guarantee; you could write your own.

    But whether you guarantee it yourself or obtain a guarantee by looking up the code of your particular standard library implementation, you can be assured that pointers and iterators to the individual elements shall remain valid:

    [C++11: 23.2.1/8]: The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invoking any move, copy, or swap operations on the individual container elements. [..]

提交回复
热议问题