08C++11右值引用
#pragma once
#pragma execution_character_set("utf-8")
#include <iostream>
using namespace std;
class Reference
{
public:
Reference()
{
cout << "Reference()..." << endl;
m_data = new int(100);
cout << "m_data:" << m_data << " *m_data:" << *m_data << endl;
}
~Reference()
{
cout << "~Reference()..." << endl;
delete m_data;
m_data = nullptr;
}
Reference(const Reference& rf)
{
cout << "Reference(const Reference& rf)..." << endl;
m_data = new int(*rf.m_data);
cout << "m_data:" << m_data << " *m_data:" << *m_data << endl;
}
Reference& operator=(const Reference& rf)
{
cout << "Reference operator=(const Reference& rf)" << endl;
if (&rf != this)
{
delete m_data;
m_data = nullptr;
m_data = new int(*rf.m_data);
}
cout << "m_data:" << m_data << " *m_data:" << *m_data << endl;
return *this;
}
Reference(Reference&& rrf)
{
cout << "Reference(Reference&& rrf)..." << endl;
m_data = rrf.m_data;
rrf.m_data = nullptr;
cout << "m_data:" << m_data << " *m_data:" << *m_data << endl;
}
Reference& operator=(Reference&& rrf)
{
cout << "Reference& operator=(Reference&& rrf)..." << endl;
if (&rrf != this)
{
delete m_data;
m_data = nullptr;
m_data = rrf.m_data;
rrf.m_data = nullptr;
}
cout << "m_data:" << m_data << " *m_data:" << *m_data << endl;
return *this;
}
private:
//右值引用主要用于处理包含堆内存等资源的对象拷贝
int* m_data;
};
//右值引用
int main()
{
//构造
Reference rf;
//拷贝构造
Reference rf1(rf);
//右值引用拷贝构造
Reference rf2(std::move(rf));
//构造
Reference rff;
//=赋值运算符
Reference rf11;
rf11 = rff;
//右值引用=赋值运算符
Reference rff2;
rff2 = std::move(rff);
return 0;
}
道虽迩,不行不至;事虽小,不为不成。