对象的生存周期

博客以一段C++代码为例,分析了临时对象的优化和引用对临时对象生命周期的影响。代码中为生成新对象时临时对象会被优化,而引用会提升临时对象的生存周期至和引用对象相同,还提及了全局对象的构造与析构情况。

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

以以下代码为例

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;
	}
	CGoods& operator=(<font color = "red">**const**</font> 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 *this;
	}
	~CGoods()
	{
		std::cout << this << " :CGoods::~CGoods()" << std::endl;
		delete[] mname;
		mname = NULL;
	}
private:
	char* mname;
	int mamount;
	float mprice;
};

int main()
{

//CGoods good1;
//good1 = 19.5; //隐式生成临时对象

CGoods good = CGoods(19.5);

CGoods& good = CGoods(19.5);
std::cout << “-----------------------” << std::endl;
return 0;
}

在上面代码中,main中绿色的一行代码实现过程中,调用了构造函数、和析构函数,为什么只生产了一个对象呢,因为临时对象的生成是为了生成新对象,所以临时对象被优化掉了
而对于紫色的代码实现过程中,调用了构造函数,没有析构函数

这是因为引用会提升临时对象的生存周期,生存周期提升到和引用对象一样

1、临时对象的优化条件:为了生成新对象时会被优化掉

CGoods good1("good1", 1, 1.1);//.data  

static CGoods good2("good2",2,2.2);
int main()
{
	CGoods good3;//
	CGoods good4(17.5f);
	CGoods good5("good5", 5, 5.5);
	static CGoods good6("good6", 6, 6.6);

	good3 = 17.5f;
	good3 = CGoods(17.5f);

	good3 = (CGoods)("good3", 3, 3.3);
	//等号右边是逗号表达式,用3。3来构造了一个临时对象

	CGoods good7 = 17.5f;
	CGoods good8 = CGoods("good8", 8, 8.8);

	CGoods & pgood9 = *(new CGoods("good9", 9, 9.9));
	//堆上生成对象,返回地址,解引用就是对象,可能会造成内存泄漏“”
	CGoods* pgood10 = new CGoods[2];

	CGoods* pgood11 = &CGoods("good11", 11, 11.11);
   //显示生成临时对象,有析构
	CGoods& rgood12 = CGoods("good12", 12, 12.12);
	//显示生成临时对象,引用提升了临时对象的生存周期-----》生成点到main函数结束,
	
	const CGoods& rgood13 = 17.5f;

	delete[] pgood10;
	delete pgood9;
	return 0;
}
CGoods good3("good3", 3, 3.3);//.data  
 static CGoods good4("good4",4,4.4);

针对上面代码,先构造全局对象 good1,good2,good3,good4,全局对象再main函数结束前析构
再构造main函数中的,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值