zoukankan      html  css  js  c++  java
  • c/c++:efficient c++,返回值优化,RVO

    返回值优化,是一种属于编译器的技术,它通过转换源代码和对象的创建来加快源代码的执行速度。

    RVO = return value optimization。

    class Complex//复数
    {
        friendd Complex operator + (const Complex & , const Complex&);
    public:
        Conplex(double r=0.0,double i= 0.0): real(r),imag(i){}
        Complex(const Complex& a):real(a.real),imag(a.imag){};
        Complex operator = (const Complex &a); 
        ~Complex();
    private:
        double real;
        double imag;
    };

     对于执行 A=B+C;

    的时候,编译器在原函数创建一个临时变量,作为第三个参数传给 operator +(),使用引用传递,然后再将值赋给 A。

    很多的编译器都实现了这样的优化,不过在程序编写的时候需要注意某些细节,才能让编译器执行这一技术。如:

    //不能使用RVO
    Complex operator +(const Complex & a, const Complex &b)
    {
        Complex retVal;
        retVal.real=a.real +b.real;
        retVal.imag=a.imag +b.imag;
        return retVal;
    }
    
    //能够使用RVO
    Complex operator +(const Complex & a, const Complex &b)
    {
        double r=a.real +b.real;
        double i=a.imag +b.imag;
        return Complex(r,i);
    }
    //不能使用RVO
    Complex operator +(const Complex & a, const Complex &b)
    {
        Complex C(a.real +b.real,a.imag +b.imag);
        return C;
    }
    
    //能够使用RVO
    Complex operator +(const Complex & a, const Complex &b)
    {
        return C(a.real +b.real,a.imag +b.imag);
    }

    另外,必须定义拷贝构造函数来“打开”RVO

    另外还有一种是通过 够着函数实现的,称 计算性构造函数

    //计算性构造函数
    Complex operator +(const Complex& a, const Complex &b)
    {
        return Complex(a,b);
    }
    
    Complex::Complex(const Complex &a ,const Complex &b):real(a.real +b.real),imag(a.imag +b.imag){}

     要点:

    1.如果必须按值返回函数,通过RVO可以省去创建和销毁局部对象的步骤。

    2.RVO 的应用要遵照编译器的实现而定。

    3.通过编写计算性函数可以更好的使用RVO。

  • 相关阅读:
    118. 杨辉三角
    1054. 距离相等的条形码
    面试题 02.01. 移除重复节点
    289. 生命游戏
    KONGA下的HAMC插件功能 --JAVA代码实现
    JPA
    Spring Cloud概述
    Spring框架分为哪七大模块,各模块的主要功能作用是什么
    ActiveMQ
    新手也能看懂,消息队列其实很简单
  • 原文地址:https://www.cnblogs.com/Azhu/p/2591489.html
Copyright © 2011-2022 走看看