C++临时对象产生的场景:
1. 值传递 2. 函数返回 3. 后置++ 等
减少临时对象产生的方法:
1. 使用引用或指针传递
2. 避免隐式类型转换
3. 使用 += 代替 +
string x = a + b; // 这里会产生保存a+b值的临时对象
string x(a); x += b; // 这样就不会产生临时对象
4. 使用前置++代替后置++
前置++的定义:
type operator++();
后置++的定义:
const type operator++(int);
为了编译器区分前置和后置++,C++规定后缀形式有一个int类型参数 ,当函数被调用时,编译器传递一个0做为int参数的值给该函数。不这样规定,无法区分,因为都仅以自身对象为入参。
class CInt {
private:
int m_value;
};
CInt & CInt:: operator++() // 前置的是没有参数的,并且返回引用
{
this -> m_value += 1;
return * this;
}
const CInt CInt::operator++(int) //后置的有一个匿名参数,并且返回const值
{
CInt old = * this;
++(*this);
return old;
}
上面的例子很好的解释了,为什么前置比后置效率高,后置会产生临时对象并返回原本的值的原因。
5. 使用匿名临时对象
#include <iostream>
using namespace std;
class Teacher
{
string name;
string course;
public:
Teacher(const char *n,const char *c):name(n),course(c)
{
cout << "创建" << course << "老师" << name <<endl;
}
Teacher(const Teacher& t)
{
name = t.name;
course = t.course;
cout << "复制" << course << "老师" << name << endl;
}
~Teacher()
{
cout << "辞退" << course << "老师" << name <<endl;
}
};
int main()
{
//用临时匿名对象来初始化一个新对象
//编译器一般会优化成直接用创建临时对象的参数来创建新对象
Teacher t1("陈宗权","C++");//构造函数
Teacher t2 = t1;//拷贝构造函数
//少建个对象 少调用个拷贝构造函数
//比较多的用的是 函数返回匿名对象 而不是有名字的临时变量。
Teacher t3 = Teacher("杨强","UC");//直接创建 调用构造函数
t2 = t3; //赋值函数
cout << "=======" <<endl;
t2 = Teacher("徐薇薇","咨询"); // 没有优化 创建匿名对象 调用赋值函数
cout << "=======" <<endl;
}
/*
创建C++老师陈宗权
复制C++老师陈宗权
创建UC老师杨强
=======
创建咨询老师徐薇薇
辞退咨询老师徐薇薇
=======
辞退UC老师杨强
辞退咨询老师徐薇薇
辞退C++老师陈宗权
*/