zoukankan      html  css  js  c++  java
  • C++11 类的六个默认函数及其使用

    六个默认函数:

    1. 构造函数(construct)
    2. 析构函数(destruct)
    3. 复制构造函数(copy construct)
    4. 赋值(assign)
    5. 移动构造函数(move construct)
    6. 移动赋值(move)

    测试代码:

    #include <iostream>
    
    using namespace std;
    
    int g_constructCount = 0;
    int g_copyConstructCount = 0;
    int g_destructCount = 0;
    int g_moveConstructCount = 0;
    int g_assignCount = 0;
    int g_moveCount = 0;
    
    struct A
    {
    
        A()
        {
            cout << "construct:" << ++g_constructCount << endl;
        }
    
        A(const A& a)
        {
            cout << "copy construct:" << ++g_copyConstructCount << endl;
        }
    
        A(A&& a)
        {
            cout << "move construct:" << ++g_moveConstructCount << endl;
        }
    
        ~A()
        {
            cout << "destruct:" << ++g_destructCount << endl;
        }
    
        A& operator=(const A& other)
        {
            cout << "assign:" << ++g_assignCount << endl;
            return *this;
        }
        A& operator=(A&& a)
        {
            cout << "move:" << ++g_moveCount << endl;
            return *this;
        }
    };

    测试:

    情形一:A a等价于A a=A();
    情形二:

    {
        A a ;
        a = A();//A()为右值,所以move
    }
    
    结果:
    construct:1
    construct:2
    move:1
    destruct:1
    destruct:2
    

    情形三: A a,b; a=b;//b为左值,所以assign
    情形四:

    {
        A a;
        A c(a);
    }
    
    结果:
    construct:1
    copy construct:1
    destruct:1
    destruct:2
    

    函数参数传递:

    void fun(A a)
    {
        cout << "funA" << endl;
    }

    情形一:

    {
        A a;
        fun(a);
    }
    
    结果:
    construct:1
    copy construct:1
    funA
    destruct:1
    destruct:2

    情形二:

    {
        A a;
        fun(move(a));
    }
    
    结果:
    construct:1
    move construct:1
    funA
    destruct:1
    destruct:2

    情形三:

    {
        fun(A());
    }
    
    结果:
    construct:1
    funA
    destruct:1

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    C#趣味程序---车牌号推断
    使用 C# 开发智能手机软件:推箱子(十四)
    【Oracle错误集锦】:ORA-12154: TNS: 无法解析指定的连接标识符
    java中你确定用对单例了吗?
    linux tty设置详解
    tty linux 打开和设置范例
    C和C++之间库的互相调用
    Android 编译参数 LOCAL_MODULE_TAGS
    pthread_once 和 pthread_key
    Android系统root破解原理分析
  • 原文地址:https://www.cnblogs.com/ggzone/p/4786408.html
Copyright © 2011-2022 走看看