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

打印结果:  

          

分析: 

  

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

猜你喜欢

转载自blog.csdn.net/free377096858/article/details/84820118