C++进阶:新人易入的那些坑 --4.编译器生成的函数

本文深入探讨了C++中编译器自动生成的四个默认成员函数:拷贝构造函数、拷贝赋值运算符、析构函数和默认构造函数。通过具体示例,解析了这些函数的工作原理和它们在不同情况下的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//########################################################################
/*
Compiler silently writes 4 functions if they are not explicitly declared
1.Copy constructor
2.Copy Assignment Operator
3.Destructor
4.Default constructor(only if there is no constructor declared).
*/

class dog {};
/* equivalent to */
class dog
{
public:
	dog(const dog& rhs)
	{
		...//Member by member initialization
	};
	dog& operator=(const dog& rhs)
	{
		//member by member copying
	};
	dog() {};
	//1.call base class's default constructor;
	//2.call data member's default constructor;
	~dog() {};
	//1.call base class's destructor;
	//2.call data member's destructor;
};
/*
1.They are public and inline.
2.They are generated only if they are needed.
*/

//Example:
class dog
{
public:
	string m_name;
	dog(string name = "Bob")
	{
		m_name = name;
		cout << "is born" << endl;
	}
	~dog()
	{
		cout << m_name << "is destroyed.\n" << endl;
	}
};

int main()
{
	dog dog1("Henry");
	dog dog2;
	dog2 = dog1;
}
/*
OUTPUT:
Henry is born.
Bob is born.
Henry is distroyed.
Henry is distroyed.
*/

/*example 2*/
class collar
{
public:
	collar()
	{
		std::cout << "collar is born.\n";
	}
};

class dog
{
	collar m_collar;
	//string& m_name;//this snippet will not be compiled
};

int main()
{
	dog dog1;
}

/*C++ 11 updata: */
class dog
{
public:
	dog() = default;
	dog(string name) { ... };
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值