c++11中增加了右值引用,
相关文章自行百度,csdn里很多,其中,std::unique_ptr 的实现就是使用了std::move
#include <iostream>
#include <vector>
#pragma warning(disable : 4996)
using namespace std;
#define PRINT(a) cout << "行" << __LINE__ << "调用:"; a
class Base
{
public :
int a;
char * buf = NULL;
void SetStr(const char * buffer)
{
if (!buffer)
return;
if (buf)
delete[] buf;
buf = new char[strlen(buffer) + 1];
strcpy(buf, buffer);
}
public:
Base() : a(1)
{
cout << "构造0-行" << __LINE__ << "\n";
}
Base(int i) : a(i)
{
cout << "构造1-行" << __LINE__ << "\n";
}
virtual ~Base()
{
cout << "析构\n";
if (buf)
delete[] buf;
}
public :
Base(const Base& other) : a(other.a)
{
SetStr(other.buf);
cout << "拷贝构造-行" << __LINE__ << "\n";
}
Base & operator=(const Base& other){
this->a = other.a;
SetStr(other.buf);
cout << "拷贝赋值-行" << __LINE__ << "\n";
return *this;
}
Base(Base&& other) // 这里不能是const类型,因为可能要更改other,
{
this->a = other.a;
this->buf = other.buf;
other.buf = NULL; // 交接堆数据空间
cout << "转移构造-行" << __LINE__ << "\n";
}
Base & operator=(Base&& other) {
this->a = other.a;
this->buf = other.buf;
other.buf = NULL; // 交接堆数据空间
cout << "转移赋值-行" << __LINE__ << "\n";
return *this;
}
public:
int getInt()
{
return a;
}
int && getRvalueInt()
{
// notice that it's fine to move a primitive type--remember, std::move is just a cast
return std::move(a);
}
};
void test1()
{
Base b1; // 构造0
//Base b2 = Base(1); // 构造1
Base b2(1); // 构造1
Base b3 = b1; // 拷贝构造
Base b4(b1); // 拷贝构造
b4 = b3; // 赋值
}
void test0()
{
Base b3 = Base(1); // 构造
Base b4 = b3; // 拷贝构造
Base b5 = std::move(b3); // 转移构造
b4 = std::move(b5); // 转移赋值
}
void test2()
{
std::vector<Base> list;
PRINT(Base b;)
//PRINT(list.push_back(b);) // 执行拷贝构造
//PRINT(list.push_back( move(b) );) // 转移构造
PRINT(list.push_back(Base(5));) // 构造临时对象,转移构造添加,临时对象析构
}
int main()
{
test2();
char m;
std::cin >> m;
}