Monday, 12 August 2013

Why returning by reference is faster than returning by value?

Why returning by reference is faster than returning by value?

class A
{
int x,y;
public:
A(int a=0,int b=0)
{x=a;y=b;}
/* ... */
}
A& fctr()
{
A loc(1,2);
return loc;
}
Let's examine this instruction :
A x=fctr();
fctr() returning a reference to an object that is destroyed ... << this
isn't the problem -_-
In the instruction above, and based on the reference returned by fctr the
program copy the destroyed object loc into x.
In other hand, returning by value copy the object loc into x !!
The only difference I see is that when returning by reference the object
loc is destroyed, but when returning by value the object loc doesn't
destroyed until the instruction is finished.
So returning by value seems safe and it do the same as returning by
reference !!
What I read in books and what I heard from people is that returning by
reference is faster than returning by value ...
So why returning by reference is fast than returning by value ?
... I think that I'm wrong in something but I don't know what is it ?!!!

No comments:

Post a Comment