1. 程式人生 > >C++:物件的生存週期

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

列印結果:  

          

分析: 

  

臨時物件的優化:
     
 臨時物件的目的若是為了生成新物件,則以生成臨時物件的方式生成新物件。
       引用能提升臨時物件的生存週期,會把臨時物件提升和引用變數相同的生存週期。