C++笔记:move语义与右值引用

来自《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;
}
相关推荐
H Journey2 个月前
C++11 新特性 右值引用与移动语义 (Rvalue References & Move Semantics)
c++11·右值引用
量子炒饭大师2 个月前
【C++11】Cyber骇客的 亡骸剥离与右值重构 ——【右值引用 与 移动语义】(附带完整代码解析)
java·c++·重构·c++11·右值引用·移动语义
Tipriest_5 个月前
C++ 中 std::move 的使用方法与注意事项
c++·move
Trouvaille ~5 个月前
【C++篇】C++11新特性详解(二):右值引用与移动语义
c++·stl·基础语法·右值引用·默认成员函数·完美转发·移动语义
点云SLAM6 个月前
C++ 右值引用(rvalue references)与移动语义(move semantics)深度详解
开发语言·c++·右值引用·移动语义·c++17·c+高级应用·代码性能优化
gcfer6 个月前
CS144 中的C++知识积累
c++·右值引用·智能指针·optional容器
艾莉丝努力练剑6 个月前
【C++:C++11收尾】解构C++可调用对象:从入门到精通,掌握function包装器与bind适配器包装器详解
java·开发语言·c++·人工智能·c++11·右值引用
月夜的风吹雨6 个月前
【C++11核心特性全面解析】:列表初始化、右值引用、移动语义与Lambda表达式深度剖析
c++11·右值引用·lambda表达式·移动语义
艾莉丝努力练剑6 个月前
【C++:C++11】详解C++11右值引用与移动语义:从性能瓶颈到零拷贝优化
java·开发语言·c++·c++11·右值引用