Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by Value and copy elision optimization

I came upon https://web.archive.org/web/20120707045924/cpp-next.com/archive/2009/08/want-speed-pass-by-value/

Author's Advice:

Don’t copy your function arguments. Instead, pass them by value and let the compiler do the copying.

However, I don't quite get what benefits are gained in the two example presented in the article:

// Don't
T& T::operator=(T const& x) // x is a reference to the source
{ 
    T tmp(x);          // copy construction of tmp does the hard work
    swap(*this, tmp);  // trade our resources for tmp's
    return *this;      // our (old) resources get destroyed with tmp 
}

vs

// DO
T& operator=(T x)    // x is a copy of the source; hard work already done
{
    swap(*this, x);  // trade our resources for x's
    return *this;    // our (old) resources get destroyed with x
}

In both cases one extra variable is created, so where are the benefits? The only benefit I see, is if the temp object is passed into second example.

like image 649
newprint Avatar asked Sep 16 '13 09:09

newprint


1 Answers

The point is that depending on how the operator is called, a copy may be elided. Assume you use your operator like this:

extern T f();
...
T value;
value = f();

If the argument is taken by by T const& the compiler has no choice but to hold on to the temporary and pass a a reference on to your assignment operator. On the other hand, when you pass the argument by value, i.e., it uses T, the value returned from f() can be located where this argument is, thereby eliding one copy. If the argument to the assignment is an lvalue in some form, it always needs to copy, of course.

like image 85
Dietmar Kühl Avatar answered Sep 19 '22 05:09

Dietmar Kühl