将一个向量移动到另一个,地址没有更新
std::move one vector to another, addresses not updated
我想将一个矢量移动到另一个矢量,而不需要复制。我发现了这个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
应该指向别的东西。有人知道为什么地址没有变吗?我想,我想知道如果编译器实际上实现了这与一个副本作为一个捷径。
您打印的是指针的地址,而不是它们所指向的地址。
打印p0
和p1
而不是&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;
相关文章:
- 我正在尝试将表的地址传递给要在另一个函数中使用的指针,但得到不兼容的指针类型
- C++ - 非静态 void* 成员,指向具有相同地址但不同值的不同对象的另一个非静态成员
- 如何保存指针地址,以便另一个指针可以继续处理它
- 内存C++复制是否将内存地址复制到另一个阵列
- 如何使用 C# 在 Windows 中获取另一个进程库地址
- 如何从另一个过程的Callstack地址检索函数名称
- 从指针数组的元素传递地址以设置另一个指针地址
- 将成员功能地址传递到另一个类功能
- mfc c++通过编辑控件设置另一个应用程序的HWND地址
- 初始化整数成员变量会导致更改另一个成员变量的地址
- 查询对象的地址,而我们正在将一个对象分配给另一个对象
- 将指针从一个向量复制到另一个向量;地址指出了变化
- 从另一个进程中查找变量的地址
- 获取C++中的另一个进程变量值(或内存地址)
- 以何种形式,可以通过管道将空指针发送到不同进程地址空间中的另一个进程
- 当用另一个指针打印时,同一指针会给出不同的地址
- 指针变量可以保存另一个指针变量的地址吗
- 是否有任何操作系统允许将内存从一个地址移动到另一个地址而不进行物理复制?
- 如何在c++中调用另一个地址空间中的函数
- 获取从另一个地址指向的地址