按值传递和复制省略优化 [英] Passing by Value and copy elision optimization

查看:85
本文介绍了按值传递和复制省略优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了文章 http://cpp-next.com / archive / 2009/08 / want-speed-pass-by-value /

作者建议:


不要复制函数参数。相反,按值传递它们,然后
让编译器执行复制。

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.

推荐答案

重点是根据调用操作员的方式,可能会删除副本。假设您这样使用运算符:

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();

如果参数由 T const& 编译器别无选择,只能保留临时文件并将引用传递给您的赋值运算符。另一方面,当您按值传递参数时,即使用 T ,则从 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.

这篇关于按值传递和复制省略优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆