zoukankan      html  css  js  c++  java
  • 临时变量,RVO,函数返回引用等等...

      开是查临时变量的相关资料 

    class A
    {
    public:
    	A()
    	{
    		cout<<"default construction"<<endl;
    	}
    	A(const A&)
    	{
    		cout<<"copy construction"<<endl;
    	}
    	A& operator =(const A& a)
    	{
    		cout<<"operator ="<<endl;
    	}
    
    	~A()
    	{
    		cout<<"destruction"<<endl;
    	}
    	int m;
    };
    
    A func()
    {
    	A a;
    	//cout<<&a<<endl;
    	return a;
    	//return A();
    }
    

      情况1: A a1=func();

    结果是调用 defaul construction

                   copy construction

                   destruction  

    说明没有产生中间变量,此时a1的初始化是调用的copy

    情况2:A a2; a2=func();

    结果是

    default construction a2
    default construction func()里的a
    copy construction    产生临时对象
    destruction             a2销毁
    operator =             调用=给a2赋值
    destruction            临时对象销毁

    此时很清楚的看到产生临时对象。

    返回值优化(Return Value Optimization,简称RVO)是编译器的一种优化

    如果把函数func改为 {return A();}

    情况1:default construction(只有一次调用 太给力了)

    情况2:

    default construction
    default construction
    operator =
    destruction
    减少了 1次copy 1次des,没有产生中的临时对象了。

     

  • 相关阅读:
    Visual Studio for Mac 2017 初体验
    利用栈求表达式的值
    Problem C: ChongQueue
    Problem G: ZL's Prob.2
    Problem F: ZL's Prob.1
    Problem B: ChongBit
    HDU 5156
    SHUOJ 1771
    OpenGL学习整理------着色器
    OpenGL ES着色器语言----------------储存修饰符
  • 原文地址:https://www.cnblogs.com/cavehubiao/p/3281753.html
Copyright © 2011-2022 走看看