码迷,mamicode.com
首页 > 编程语言 > 详细

关于c++的效率

时间:2015-04-03 01:23:53      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

最近读书,感觉c++中有两点比较影响效率

1、是临时对象的构造和析构。为了避免临时对象的产生,c++的编译器做了很多的优化。比如对象的构造函数的初始化列表,还有nrv优化,

 

2、	class tclass
3、	{
4、	public:
5、	 tclass():temp("")
6、	{
7、	
8、	}
9、	
10、	string temp;
11、	};

 

 使用初始化列表时,编译器在生成构造函数时会避免一个临时对象的产生。不采用初始化别表,编译器生成的构造函数如下:

class tclass
{
public:
 tclass():data("")
{
   string temp ="";
   data = temp;

}

string data;
};

 

 

NRV 优化指的是,对象以函数值返回时,编译器对代码进行的优化,编译器对代码优化之前

 

void fun()
{
  string temp;
  temp = test();
}
string test()
{
string temp;
 return temp
}

 

 优化之后是这样的:

 

12、	void fun()
13、	{
14、	  string temp;
15、	  temp = test();
16、	}
17、	void test(string& temp)
18、	{
19、	
20、	 return ;
21、	}

 NRV优化的前提是,对象需要提供复制构造函数,在提供拷贝构造函数时,才能激活编译器中的NRV优化

还有一点是虚函数造成的动态绑定,虚函数形成的多态机制,使程序只有在运行的时候才能确定具体那个函数被调用,这个也会一定程度的影响效率。

 

关于c++的效率

标签:

原文地址:http://www.cnblogs.com/xgcode/p/4388887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!