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
    */

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    优秀的JavaScript模块是怎样炼成的(转发)
    从发展历史理解 ES6 Module(转发)
    JavaScript 模块演化简史(转发)
    objcopy 格式转换
    链接操作
    fflush()
    为什么栈地址从高到低生长,堆从低到高
    C语言中,a[-1] (负数下标)的用途
    va_list 、va_start、 va_arg、 va_end 使用说明
    docker 部署 redis
  • 原文地址:https://www.cnblogs.com/hujianglang/p/6637479.html
Copyright © 2011-2022 走看看