C++:对象的生存周期

  • 显示对象:出现类型名
  • 隐式对象:不出现类型名

   注意: 临时对象的生存周期只在本条语句,临时对象一旦被引用,它的生存周期就和引用相同。

临时量 内置类型自定义类型
隐式常量常量
显式常量变量

 

 

                                                                                                                                               

实例分析:

#include<iostream>
#pragma warning(disable:4996)
#pragma warning(disable:4305)//double 与 float

class CGoods
{
public:
	CGoods(char* name, float price, int amount)
	{
		std::cout << this << " :CGoods::CGoods(char*,float, int)" << std::endl;
		mname = new char[strlen(name) + 1]();
		strcpy(mname, name);
		mprice = price;
		mamount = amount;
	}
	CGoods(int amount)
	{
		std::cout << this << " :CGoods::CGoods(int)" << std::endl;
		mname = new char[1]();
		mamount = amount;
	}
	CGoods()
	{
		std::cout << this << " :CGoods::CGoods()" << std::endl;
		mname = new char[1]();
	}
	~CGoods()
	{
		std::cout << this << " :CGoods::~CGoods()" << std::endl;
		delete[] mname;
		mname = NULL;
	}
	CGoods(const CGoods& rhs)
	{
		std::cout << this << " :CGoods::CGoods(const CGoods&)" << std::endl;
		mname = new char[strlen(rhs.mname) + 1]();
		strcpy(mname, rhs.mname);
		mprice = rhs.mprice;
		mamount = rhs.mamount;
	}
	CGoods& operator=(const CGoods& rhs)
	{
		std::cout << this << " :CGoods::operator=(const CGoods&)" << std::endl;
		if (this != &rhs)
		{
			delete[] mname;
			mname = new char[strlen(rhs.mname) + 1]();
			strcpy(mname, rhs.mname);
			mprice = rhs.mprice;
			mamount = rhs.mamount;
		}
		return *this;
	}
private:
	char* mname;
	float mprice;
	int mamount;
};

CGoods ggood1("good1", 10.1, 20);//.data
int main()
{
	CGoods good3;
	CGoods good4(good3);

	good4 = good3;

	static CGoods good5("good5", 10.1, 20);//.data

	CGoods good6 = 10;
	CGoods good7(10);
	CGoods good8 = CGoods("good8", 10.1, 20);

	good6 = 20;
	good7 = CGoods(20);
	good8 = (CGoods)("good8", 10.1, 20);

	CGoods* pgood9 = new CGoods("good9", 10.1, 20);//heap
	CGoods* pgood10 = new CGoods[2];

	std::cout << "------------------" << std::endl;
	CGoods* pgood11 = &CGoods("good11", 10.1, 20);
	std::cout << "------------------" << std::endl;
	//CGoods* pgood12 = 20;
	CGoods& rgood12 = CGoods("good11", 10.1, 20);
	std::cout << "------------------" << std::endl;
	const CGoods& rgood13 = 20;

	delete pgood9;
	delete[] pgood10;

	return 0;
}
CGoods ggood2("good2", 10.1, 20);//.data

打印结果:  

          

分析: 

  

临时对象的优化:
     
 临时对象的目的若是为了生成新对象,则以生成临时对象的方式生成新对象。
       引用能提升临时对象的生存周期,会把临时对象提升和引用变量相同的生存周期。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值