How do vector elements preserve their original address after a vector std::move?

  • A+

As you can see in the output, the objects of the vector pre not only "moved" to the vector post, but also preserved their original address space in memory. What is really going on behind this move? Is this behaviour expected? Say I need to have a separate vector of pointers to these objects, is it safe to assume that after this move the objects will always have their original addresses?

Actually, I have a class containing a vector like this and the vector of pointers I mentioned as members. I have also deleted the copy ctors, and defined the move ones for the class.

#include <iostream> #include <vector>  struct B {     int val = 0;        B(int aInt) : val(aInt) {  }; };  int main() {      std::vector<B> pre;      pre.push_back(B(1));     pre.push_back(B(2));     std::cout << "pre-move:/t" << (void*)& << '/n';     std::cout << "pre-move:/t" << (void*)& << '/n';      std::vector<B> post(std::move(pre));      std::cout << "post-move:/t" << (void*)& << '/n';     std::cout << "post-move:/t" << (void*)& << '/n';      return 0; } 


pre-move:   0x1d7b150  pre-move:   0x1d7b154 <------| post-move:  0x1d7b150        | post-move:  0x1d7b154 <------| 


A vector is basically nothing more than a pointer to heap-allocated memory, the current length and the current capacity of the vector.

By "moving" a vector, all you're doing is copying those values, and resetting the values of the moved-from vector.

For the data of the vector, it's basically equivalent to

original_pointer = some_place_in_memory; new_pointer = original_pointer;   // Copies the *value* of original_pointer original_pointer = nullptr; 

There's no need to allocate new memory and copy the data in the vector.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: