通过Value和复制省略优化

时间:2013-09-16 09:50:53

标签: c++ compiler-optimization copy-elision

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

作者的建议:

  

不要复制你的函数参数。相反,通过值传递它们   让编译器进行复制。

但是,我并没有从文章中提到的两个例子中获得什么好处:

//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
    }

在这两种情况下都会创建一个额外的变量,那么好处在哪里? 我看到的唯一好处是,如果将temp对象传递给第二个示例。

1 个答案:

答案 0 :(得分:6)

关键在于,根据操作员的调用方式,可能会省略副本。假设您使用这样的运算符:

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

如果参数由T const&获取,则编译器别无选择,只能保留临时值并将引用传递给赋值运算符。另一方面,当您通过值传递参数时,即它使用T时,从f()返回的值可以位于此参数所在的位置,从而删除一个副本。如果赋值的参数是某种形式的左值,那么它总是需要复制。