将一个向量移动到另一个,地址没有更新

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

本文关键字:另一个 地址 更新 移动 向量 一个      更新时间:2023-10-16

我想将一个矢量移动到另一个矢量,而不需要复制。我发现了这个STL向量:移动向量的所有元素。我想测试一下,所以我编写了一个简单的例子:

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;