c++ - std::move 一个 vector 到另一个 vector ,地址不更新

标签 c++ vector stl move

我想在没有拷贝的情况下将一个 vector move 到另一个 vector 。我找到了这个 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

关于c++ - std::move 一个 vector 到另一个 vector ,地址不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32640564/

相关文章:

c++ - checkCudaErrors没有打印错误信息

c++ - 如何绘制存储在 vector 中的 SFML 形状

java - vector 中参数的匹配

c++ - C++:交换两个不同 vector 的两个元素

C++ STL vector 迭代器...但出现运行时错误

c++ - 按值与按引用的 STL 容器对象

c++ - 检测非继承 typedef 的特征

c++ - AQTime DLL 分析 - 无结果

FreeBasic 中带有 ScreenRes 的 C++ 等价函数

c++ - 使用 std::future 无效使用不完整类型