众所周知,类是C++的核心,而对于类的生存周期的长短是受到很多因素影响,在这里我从以下几个方面来分析:
- 类在.data段生成时的生存周期
- 类在栈区生成时的生存周期
- 类在堆区生成时的生存周期
为了体现各种情况下类的生存周期,我们写一个测试用例来直观地感受。
class CGoods//实现三种构造方式 一个拷贝构造函数 一个赋值运算符重载
{
public:
CGoods(char* name, int amount, float price)
{
std::cout << this << " :CGoods::CGoods(char*,int,float)" << std::endl;
mname = new char[strlen(name) + 1];
strcpy(mname, name);
mamount = amount;
mprice = price;
}
CGoods()
{
std::cout << this << " :CGoods::CGoods()" << std::endl;
mname = new char[1];
}
CGoods(float price)
{
std::cout << this << " :CGoods::CGoods(float)" << std::endl;
mname = new char[1];
mprice = price;
}
CGoods(const CGoods& rhs)
{
std::cout << this << " :CGoods::CGoods(const CGoods& )" << std::endl;
mname = new char[strlen(rhs.mname) + 1];
strcpy(mname, rhs.mname);
mamount = rhs.mamount;
mprice = rhs.mprice;
}
/*
const
1.防止实参被修改
2.接收隐式生成的临时量
*/
CGoods& operator=(const CGoods& rhs)
{
std::cout << this << " :CGoods::operator=(const CGoods&) <<==" << &rhs << std::endl;
if (this != &rhs)
{
delete[] mname;
mname = new char[strlen(rhs.mname) + 1];
strcpy(mname, rhs.mname);
mamount = rhs.mamount;
mprice = rhs.mprice;
}
return *thi