C++ 性能优化篇:---temporary objects

来源:互联网 发布:数控r角怎么编程 编辑:程序博客网 时间:2024/06/10 22:57

C++ 新能优化篇:---temporaryobjects

 

Chapter one: where temporaryobjects produce

         (1)type mismatch:  {

         Friend Rational operator+(constRational& ,const Rational& );

//using friend function instead of memberfuncition’ strength is  the firstparameter can freely //converted

         Public:

                   Rational(int a=0,int b =1):m(a),n(b){}

Private:

         Intm;

         Intn;

 

}

For instance;    Rational rational = 4;

将上述转化为类似C的伪代码技术

Rational temp(4);

Rational rational = temp;

 

引出的知识:explicit

消除方法:overload Rational& operator = (int a)

(2)pass by value :很常见就不举例了,主要优先使用引用,次为指针;

(3)return by value:

虽然RVO可以消除一部分,但是在有异常throw ,多返回点,创建有临时返回对象的时候就会失效。

(4)前缀与后缀,++a,a++ 尽量用前缀;

 

Solution:

1,使用复合运算符号-=,+=等代替=

2,使用计算性构造函数来尽量使编译器实现RVO;

3,使用C++11的新特性右值引用和move语义,在设计类的时候创建moveconstructor and move operator =

4  优先用初始化列表,和复制构造函数代替在函数体中第一和赋值构造函数

5,缓式构造,变量直到使用的使用的时候才初始化。

原创粉丝点击