以以下代码为例
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函数中的,