zoukankan      html  css  js  c++  java
  • C++程序设计方法3:移动构造函数

    移动拷贝构造函数

    语法:

    ClassName(ClassName&&);

    目的:

    用来偷“临时变量”中的资源(比如内存)

    临时变量被编译器设置为常量形式,使用拷贝构造函数无法将资源偷出来(“偷”是对原来对象的一种改动,违反常量的限制)

    基于“右值引用“定义的移动构造函数支持接受临时变量,能偷出临时变量中的资源;

    #include <iostream>
    using namespace std;
    
    class Test
    {
    public:
        int *buf;//only for demo
        Test()
        {
            buf = new int(3);
            cout << "Test():this->buf@ " << hex << buf << endl;
        }
        ~Test()
        {
            cout << "~Test(): this->buf@" << hex << buf << endl;
            if (buf)
                delete buf;
        }
    
        Test(const Test& t) :buf(new int(*t.buf))
        {
            cout << "Test(const Test&) called.this->buf@" << hex << buf << endl;
        }
    
        Test(Test&& t) :buf(t.buf)
        {
            cout << "Test(Test&&) called.this->buf@" << hex << buf << endl;
            t.buf = nullptr;
        }
    };
    
    Test GetTemp()
    {
        Test tmp;
        cout << "GetTemp(): tmp.buf@" << hex << tmp.buf << endl;
        return tmp;//返回给未知名字的对象
    }
    
    void fun(Test t)
    {
        cout << "fun(Test t):t.buf@ " << hex << t.buf << endl;
    }
    
    int main()
    {
        Test a = GetTemp();
        cout << "main():a.buf@" << hex << a.buf << endl;
        fun(a);//拷贝调用
        return 0;
    }

    //备注:编译器对返回值做了优化,因此增加编译选项,禁止编译器进行返回值的优化
    /*
    g++ wo2.cpp --std=c++11 -fno-elide-constructors
    */

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    腾讯游戏是如何使用Docker的
    为Elasticsearch添加中文分词,对比分词器效果
    13个对web设计师有用的JavaScript插件
    七牛是如何搞定每天500亿条日志的
    七牛李道兵谈“架构坏味道”
    接口的解释
    数组
    Div Span
    dl dt dd
    @Razor解析器
  • 原文地址:https://www.cnblogs.com/hujianglang/p/6637479.html
Copyright © 2011-2022 走看看