设为首页 加入收藏

TOP

C++临时对象减少的方法
2015-07-20 18:01:10 来源: 作者: 【 】 浏览:2
Tags:++临时 对象 减少 方法

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 <
   
    

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU1196 Lowest Bit 下一篇POJ 3020 Antenna Placement ,二..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: