Passing by Value and copy elision optimization

房东的猫 提交于 2019-12-09 17:23:26

问题


I came upon the article http://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.


回答1:


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.



来源:https://stackoverflow.com/questions/18825040/passing-by-value-and-copy-elision-optimization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!