Kavish  Dwivedi
Kavish Dwivedi

Reputation: 745

What is the difference between the two forms of returning object?

I was trying overloading binary + for an Integer class created as:

const Integer operator+(const Integer& left,const Integer& right) 
{
    return Integer(left.i + right.i);
}

and

 const Integer operator+(const Integer& left,const Integer& right)
 {
     Integer tmp(left.i + right.i);
     return tmp;
 }

Now what I learnt was that in the first case a temporary Integer object is created and is returned and in the second case the usual object creation using constructor call and then copying and then calling destructor takes place. What Ecekl has said for the first one is that the compiler takes advantage of this by building the object directly into the location of the outside return value.What do we infer from this ? I read about the return value optimization but couldn't get what it means by copying directly into the location thing.

Upvotes: 3

Views: 83

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126432

There is absolutely no difference, and in most situations a decent compiler will optimize the second form into the first - and will perform copy/move elision by Named Return Value Optimization (NRVO) when returning tmp.

You might want to use the second form if it makes the code more readable for you, or easier to maintain and/or debug. If you are concerned with performance, there's no reason (unless you turned off compiler optimizations, but that would suggest you're not interested in performance in the first place).

Notice, however, that returning a const Integer does not make a lot of sense. Since you are returning by value, you should rather return an Integer:

Integer operator + (const Integer& left, const Integer& right) 
{
    return Integer(left.i + right.i);
}

As a final remark, this could even be rewritten as follows, provided that Integer has a non-explicit constructor accepting an int (notice, that this is usually not the case, since constructors accepting one argument are generally marked as explicit to avoid awkward implicit conversions):

Integer operator + (const Integer& left, const Integer& right) 
{
    return left.i + right.i;
}

Upvotes: 6

Related Questions