Search code examples
c++vectorstlmove

std::move one vector to another, addresses not updated


I want to move one vector to another without a copy. I found this STL vector: Moving all elements of a vector. I wanted to test it out so I coded up a simple example below.

C++ compiler version:

g++ 5.1.0 on (Ubuntu 5.1.0-0ubuntu11~14.04.1)

I am compiling using the following command:

g++ -std=c++14 test2.cpp -o test2

Here is the code, I have written:

#include <iostream>
#include <memory>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
  vector<uint8_t> v0 = { 'h', 'e', 'l', 'l', 'o' };
  vector<uint8_t> v1 = {};

  // pointer to the data
  // portion of the vector
  uint8_t* p0 = v0.data();
  uint8_t* p1 = v1.data();

  // for stdout
  string s0(v0.begin(), v0.end());
  string s1(v1.begin(), v1.end());

  cout << "s0='" << s0 << "' addr=" << &p0 << endl;
  cout << "s1='" << s1 << "' addr=" << &p1 <<endl;

  /// here i would think the pointer to the data in v1
  /// would point to v0 and the pointer to the data in v0
  /// would be something else.
  v1 = move(v0);

  p0 = v0.data();
  p1 = v1.data();

  s0.assign(v0.begin(), v0.end());
  s1.assign(v1.begin(), v1.end());

  cout << "s0='" << s0 << "' addr=" << &p0 << endl;
  cout << "s1='" << s1 << "' addr=" << &p1 << endl;  
}

and here is the output:

s0='hello' addr=0x7fff33f1e8d0
s1='' addr=0x7fff33f1e8d8
s0='' addr=0x7fff33f1e8d0
s1='hello' addr=0x7fff33f1e8d8

If you see the output the addresses have not changed at all. I would think the address for p1 would have the address for p0 and p0 would point to something else. Does anyone know why the addresses have not changed? I guess, I'm wondering if the compiler actually implemented this with a copy as a short cut.


Solution

  • You want:

    cout << "s0='" << s0 << "' addr=" << (void*) p0 << endl;
    cout << "s1='" << s1 << "' addr=" << (void*) p1 << endl;
    

    instead of:

    cout << "s0='" << s0 << "' addr=" << &p0 << endl;
    cout << "s1='" << s1 << "' addr=" << &p1 <<endl;