C++11 类的六个默认函数及其使用

来源:互联网 发布:淘宝自动充值平台 编辑:程序博客网 时间:2024/06/07 14:18

六个默认函数:

  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:1construct:2move:1destruct:1destruct:2

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

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

函数参数传递:

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

情形一:

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

情形二:

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

情形三:

{    fun(A());}结果:construct:1funAdestruct:1
0 2
原创粉丝点击