5

Possible Duplicate:
Does moving a vector invalidate iterators?

Consider the following codes:

std::vector<T> prepare(T*& data) {
    std::vector<T> buffer;
    // Fill in buffer.
    data = buffer.data();
    return buffer;
}

...

T* data;
auto vec = prepare(data);
// line 12

Is it possible that vec.data() != data in line 12? Similarly,

std::vector<T> buffer;
// ... Fill in buffer ...
T* data = buffer.data();
auto vec = std::move(buffer);
// line 5

Is it possible that vec.data() != data in line 5?

Practically both are not possible in the implementation of libstdc++ and libc++, because the move constructors are implemented as simple pointer assignments, but it seems the standard does not specify anything on it (similar to Is the capacity required to be preserved when moving a std::vector?). Can the "constant complexity" guarantee that vec.data() == data?

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005

1 Answers1

0

Constant complexity means the container isn't allowed to copy/move individual elements, so it must transfer ownership of the existing storage to the new object, so the pointer returned by data() must be the same.

For move assignment (rather than move construction) that is only true if propagate_on_container_move_assignment is true for the vector's allocator type or the allocators compare equal.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521