Boost logo

Boost :

From: AlisdairM (alisdair.meredith_at_[hidden])
Date: 2004-01-11 06:48:40


David Abrahams <dave_at_[hidden]> wrote in
news:smio1qsb.fsf_at_[hidden]:

> Yep, my tests show the same. That's a relief to me, actually. I
> wonder what Andrei was on about?

IIUC, it all depends on what you are doing with the parameter. If you are
pasing by reference only to defer making a copy, then he found places this
is a pessimisation. OTOH, if you MUST make a copy anyway (such as
initialising member data in a constructor) then clearly pass-by-value must
involve an extra copy (that may be elided depending on compiler) and so
pass-by-ref is going to be preferred.

Eg:

void StringDemo( const std::string &s )
{
  std::string sResult( s );
  s += ": result";
  std::cout << sResult << std::endl;
}

void StringDemo( std::string s )
{
  s += ": result";
  std::cout << s << std::endl;
}

int main()
{
  StringDemo1( "Hello world" );
  StringDemo2( "Hello world" );
}

I belive demo 2 may involve 1 fewer temporary string objects, or at least,
it is far easier to elide the temporary copy.

As mentioned, this is also not the case in the constructor under
discussion, where pass-by-ref should win.

AlisdairM


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk