zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    群发邮件2
    谈谈C#中的三个关键词new , virtual , override
    一个简单的jQuery插件ajaxfileupload实现ajax上传文件例子
    网站静态化结构
    第四十七章 天神的邀请
    asp.net 异步群发邮件时遭遇到的问题 ddddddddd
    第四十章 远方的消息
    商用群发p2p网络
    第四十八章 三大客卿
    第四十五章 你没让我失望
  • 原文地址:https://www.cnblogs.com/rock-cc/p/13169733.html
Copyright © 2011-2022 走看看