std::move 一个向量到另一个向量,地址未更新

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

我想在没有副本的情况下将一个矢量移动到另一个矢量。我找到了这个 STL vector: Moving all elements of a vector。我想测试一下,所以我在下面编写了一个简单的示例。

C++ 编译器版本:

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

我正在使用以下命令进行编译:

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

这是我写的代码:

#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;  
}

这是输出:

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

如果您看到输出地址根本没有改变。我认为 p1 的地址会有 p0 的地址,而 p0 会指向别的东西。有谁知道为什么地址没有改变?我想,我想知道编译器是否真的使用副本作为捷径来实现它。

您正在打印指针的地址,而不是它们指向的地址。

打印 p0p1 而不是 &p0&p1

你想要:

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

而不是:

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