可以取地址的是左值,左值在內存中不在寄存器;int a; char b; a,b 都是左值;
去不了地址的都是右值,右值不在內村中實在寄存器內部; int c= a+b ;"a+b" 就是一個右值
move()可以實現將一個左值轉換爲右值的功能
// std::swap
#include <iostream>
#include <vector> // std::vector
#include <algorithm>
using namespace std;
class A
{
int *p;
public:
A(int value) : p(new int(value))
{
cout << "create obj " << p << endl;
}
~A()
{
std::cout << "delete pointer: " << p << std::endl;
//查看析夠函數刪除了哪個指針
if (p != nullptr)
{
delete p;
}
}
A(A &&a)
{
if (this != &a)
{
p = a.p;
a.p = nullptr;
cout << " move " << p << endl;
}
else
{
cout << "move self" << endl;
}
}
A(const A &a)
{
if (this != &a)
{
p = new int(233);
*p = *(a.p);
cout << " copy " << p << endl;
}
else
{
cout << "copy self" << endl;
}
}
A &operator=(A &&a)
{
if (this != &a)
{
p = a.p;
a.p = nullptr;
cout << " && == move" << p << endl;
return *this;
}
else
{
cout << "move = self" << endl;
}
}
A &operator=(const A &a)
{
if (this != &a)
{
p = new int(233);
*p = *(a.p);
cout << " & == copy" << p << endl;
}
else
{
cout << "copy = self" << endl;
}
return *this;
}
void print(A &a)
{
cout << "print " << (a.p) << endl;
// A b = a;
//a.p=nullptr;
}
};
//總結: 只有變量之間賦值纔會使用賦值運算符“=”
// 使用一個對象初始化新建對象都是使用移動或者是複製構造函數;
int main()
{
vector<A> vec;
{
A a(1);
//A b(2);
//A b(move(a)); //移動構造函數
//A e(a);//複製構造函數
//A d =move(a);//移動構造函數
//A c=a; //複製構造函數
// a.print(a);
// getchar();
//std::swap(a,b);
//A c(2);
//c=a;//使用了複製賦值函數
//c =move(a); //使用了移動賦值函數
//c.print(c);
//自己移動自己和自己複製自己測試
//a=(move(a)); //如果沒有if(this!=&a)則會產生錯誤
//a = a;//
//容器測試:容器可以使用複製構造函數也可以使用移動構造函數給容器添加元素
//vec.push_back(move(a)); //使用了移動構造函數
//vec.push_back(a);//使用了複製構造函數
}
getchar();
}