X bar()

{

   X xx;

   // process xx ...

   return xx;

}

编译器会将其转化为:

// function transformation to reflect

// application of copy constructor

// Pseudo C++ Code

void

bar( X& __result )

{

   X xx;

 

   // compiler generated invocation

   // of default constructor

   xx.X::X();

 

   // ... process xx

   // compiler generated invocation

   // of copy constructor

   __result.X::X( xx );

 

   return;

}

若编译器支持NRV(Named Return Value )优化,则会转化为:

 

void

bar( X &__result )

{

   // default constructor invocation

   // Pseudo C++ Code

   __result.X::X();

 

   // ... process in __result directly

 

   return;

}

 NRV将剔除copy constructor的执行

e.g.

 

#include <stdio.h>
class Rational
{
public:
 Rational(int _a = 0,int _b=0)
 {
  a = _a ;
  b = _b ;
  printf("Rational()%d\n",b) ;
 }

 Rational(const Rational &src)
 {
  this->b = src.b+1 ;
  printf("Rational(Rational&)%d\n",b) ;
 }
 ~Rational()
 {
  printf("~Rational()%d\n",b) ;
 }
 int a,b;
};

const Rational fun(Rational t)
{
  Rational tt;
 return tt ;
}
int main()
{
 Rational t(1,2) ;
 Rational t2=fun(t) ;

 return 0 ;
}

若没有NRV优化,结果为:

Rational()2
Rational(Rational&)3
Rational()0
Rational(Rational&)1
~Rational()0
~Rational()3
~Rational()1
~Rational()2

若有NRV优化则为:

Rational()2
Rational(Rational&)3
Rational()0
~Rational()3
~Rational()0
~Rational()2

Posted on 2009-06-04 12:42  阳阳爸爸  阅读(188)  评论(0编辑  收藏  举报