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
using namespace std;
class Teacher
{
string name;
string course;
public:
Teacher(const char *n,const char *c):name(n),course(c)
{
cout << "创建" << course << "老师" << name <