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

  • 相关阅读:
    LF will be replaced by CRLF in package.json.
    JS 防抖和节流
    webpack依赖分析|打包优化
    JavaScript 中精度问题以及解决方案
    mysql查询某些数据的最小值
    mongodb sort
    常用的快捷键(用到时再不断完善)
    一、negut增加Nancy,和Nancy.Hosting.Self,
    Linux系统(Centos)安装tomcat和部署Web项目
    CentOS 7系统安装jdk-8u161-linux-x64.tar.gz
  • 原文地址:https://www.cnblogs.com/rock-cc/p/13169733.html
Copyright © 2011-2022 走看看