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

发布于:2021-07-19 23:22:05

六个默认函数:


    构造函数(construct)析构函数(destruct)复制构造函数(copy construct)赋值(assign)移动构造函数(move construct)移动赋值(move)

测试代码:


#include

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

相关推荐

最新更新

猜你喜欢