[C++] Returning objects from a function and performance

From: Spacen Jasset (spacenjasset_at_yahoo.co.uk)
Date: 02/21/05


Date: 21 Feb 2005 15:18:03 +0100

If I have a function that resturns a class object. i.e.

ExtString mid( int start, int len )
{
        ExtString result;
        ...
        return result;
}

Then the compiler must invoke the copy constructor of ExtString to make
a copy and return it. Unless ofcourse it can be optimised. But surpose
the function is like this:

ExtString mid( int start, int len )
{
        ExtString result1;
        ExtString result2;

        if ( /* something )
                return result1;
        else
                return result2;
}

The compiler would have a harder time optimising that I suspect.

I ask this question becuase I've been told that this is all very
inefficient and the 'mid' and other functions have been re-written in
our library to take a refrence like this:

void mid( ExtString &sub, int start, int len )
{
...
}

Is returning a potentially large object from a function as bad as it
seems? I notice the std::string.substring() function also returns a
string object. This looks like a popular thing to do in C++.

It's still traditional amoung C programmers to never return structures
by value, despite being able to do so officialy since C89. Presumably
there is a considerable performance problem for large objects in C++,
but perhaps notso in C since there are no copy constructors, and the
compiler can avoid any object copy on return.