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

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

  • 相关阅读:
    算法竞赛入门经典习题2-3 韩信点兵
    ios入门之c语言篇——基本函数——5——素数判断
    ios入门之c语言篇——基本函数——4——数值交换函数
    144. Binary Tree Preorder Traversal
    143. Reorder List
    142. Linked List Cycle II
    139. Word Break
    138. Copy List with Random Pointer
    137. Single Number II
    135. Candy
  • 原文地址:https://www.cnblogs.com/ggzone/p/4786408.html
Copyright © 2011-2022 走看看