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

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    进制转换
    01背包基础
    6-14 Inspector s Dilemma uva12118(欧拉道路)
    9-4 Unidirectional TSP uva116 (DP)
    8-4 奖品的价值 uva11491(贪心)
    9-1 A Spy in the Metro uva1025 城市里的间谍 (DP)
    8-3 Bits Equalizer uva12545
    8-2 Party Games uva1610 (贪心)
    自动发邮件功能
    窗口截图.py
  • 原文地址:https://www.cnblogs.com/hujianglang/p/6637479.html
Copyright © 2011-2022 走看看