C++11 std::move
1. 左值,右值
int a = 1;2. 左值引用,右值引用
int a = 1;
int& a_ref = a; // 左值引用指向左值
const int& a_ref1 = 1; // const左值引用可以指向右值
int&& a_ref_r = 1; // 右值引用指向右值
int&& a_ref_r1 = std::move(a); // std::move可以把左值转为右值引用3. 移动构造函数函数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
class A
{
public:
A()
: res_(NULL)
{
res_ = new char[128];
}
// 拷贝构造,需要复制资源
A(const A& a)
{
res_ = new char[128];
memcpy(res_, a.res_, 128);
}
// 移动构造,直接转移资源
A(A&& a)
{
res_ = a.res_;
a.res_ = NULL;
}
~A()
{
}
void* Resource()
{
return res_;
}
private:
char* res_;
};
int main()
{
A a = A();
A b = a;
printf("a %p b %p\n", a.Resource(), b.Resource());
A c = std::move(a);
printf("a %p b %p c %p\n", a.Resource(), b.Resource(), c.Resource());
return 0;
}
a 0xf4a010 b 0xf4a0a0
a (nil) b 0xf4a0a0 c 0xf4a010最后更新于