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
  • 相关阅读:
    开通了
    A computer hardware platform abstraction
    脑机接口入门概览
    JDK自带VM分析工具jps,jstat,jmap,jconsole
    泛型里的super和extend
    动态规划
    用二分法查找的套路(一)
    A computer hardware platform abstraction
    CentOS7安装JDK1.8
    CentOS7如何修改hostname
  • 原文地址:https://www.cnblogs.com/ggzone/p/10121261.html
Copyright © 2011-2022 走看看