• 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;
    }
    
    

    image

  • 相关阅读:
    linux tcp/ip 调优
    ulimit 管理系统资源
    linux grep 设置高亮显示
    linux 调整内核优化
    微信公众平台自定义菜单及高级接口PHP SDK
    微信公众平台开发(102) 模版消息
    微信WeixinJSBridge API
    微信支付开发(2) 静态链接Native支付
    微信分享JS接口失效说明及解决方案
    微信JS接口
  • 原文地址:https://www.cnblogs.com/rock-cc/p/13169733.html
Copyright © 2020-2023  润新知