来自《c++标准库 第2版》
1. Move语义与右值引用





2. 右值、左值引用的重载规则

3. 返回右值引用

4. 测试代码
cpp
#include <iostream>
#include <chrono>
#include <fstream>
class MyBinData
{
public:
MyBinData()
{
m_pBuffer = nullptr;
m_nBytes = 0;
}
MyBinData(const char* pData, uint32_t nSize)
{
m_pBuffer = new char[nSize];
memcpy_s(m_pBuffer, nSize, pData, nSize);
m_nBytes = nSize;
}
virtual ~MyBinData()
{
if (m_pBuffer)
{
delete[] m_pBuffer;
m_pBuffer = 0;
m_nBytes = 0;
}
std::cout << "deconstructor is called" << std::endl;
}
MyBinData(const MyBinData& other)
{
m_nBytes = other.m_nBytes;
if (m_nBytes > 0)
{
m_pBuffer = new char[other.m_nBytes];
memcpy_s(m_pBuffer, m_nBytes, other.m_pBuffer, other.m_nBytes);
}
else
{
m_pBuffer = nullptr;
}
}
MyBinData(MyBinData&& other) noexcept
{
m_pBuffer = other.m_pBuffer;
m_nBytes = other.m_nBytes;
other.m_pBuffer = nullptr;
other.m_nBytes = 0;
}
MyBinData& operator=(MyBinData&& other) noexcept
{
if (this == &other)
{
return *this;
}
delete[] m_pBuffer;
m_pBuffer = other.m_pBuffer;
m_nBytes = other.m_nBytes;
other.m_pBuffer = nullptr;
other.m_nBytes = 0;
return *this;
}
MyBinData& operator=(const MyBinData& other)
{
if (this == &other)
{
return *this;
}
if (m_pBuffer) delete[] m_pBuffer;
m_nBytes = other.m_nBytes;
if (m_nBytes > 0)
{
m_pBuffer = new char[other.m_nBytes];
memcpy_s(m_pBuffer, m_nBytes, other.m_pBuffer, other.m_nBytes);
}
else
{
m_pBuffer = nullptr;
}
return *this;
}
private:
char* m_pBuffer;
uint32_t m_nBytes;
};
int main()
{
MyBinData mData("aaaaaa", 7);
MyBinData mData2 = std::move(mData);
std::cout << "ending" << std::endl;
return 0;
}