Question

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 correct solution

OTHER TIPS

Returning by reference - System don't need to allocate & initialise any extra memory. Just have to pass the memory address of already existing location.

Returning by value - System need to allocate & initialise extra memory.

It completely depends on the requirements whether you need "by reference" or "by value".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top