在某些情况下,完美的转发实际上可以提高性能吗?

问题描述 投票:1回答:1

我不确定我是否正确理解完善的转发。我已经测试了两个功能:

template <typename T,typename Arg>
T createA(Arg&& a){
  return T(std::forward<Arg>(a));
}


template <typename T,typename Arg>
T createB(Arg a){
  return T(std::move(a));
}

compared the compiled code。优化似乎没有任何区别。与正常的按值传递和跟随移动相比,实际上在实践中使用完美的转发是否会提高性能?我使用错误的方式吗?

编辑:更改了代码以使用模板功能

c++ c++11 perfect-forwarding
1个回答
0
投票

您基本上有那些构造函数选项:

class myclass {
public:
    // #1 myclass(const std::string& s) : s(s) {}
    // #2 myclass(std::string&& s) : s(std::move(s)) {}

    // #3 myclass(std::string s) : s(std::move(s)) {}

    // #4 template <typename T> myclass(T&& t) : s(std::forward<T>(t)) {}

    std::string s;
};

#3不能与#1#2->歧义通话一起出现

并致电

std::string s;
myclass A(s);
myclass B(std::move(s));
myclass C("temporary");
myclass D({5, '*'});

以下为复制/移动构造函数的数量

                        | A | B | C | D |
------------------------|---|---|---|---|
1                  Copy | 1 | 1 | 1 | 1 |
const l-value ref  Move | 0 | 1 | 0 | 0 |
                  Other | 0 | 0 | 1 | 1 |
------------------------|---|-v-|-v-|-v-|
2                  Copy | X | 0 | 0 | 0 |
r-value ref        Move | X | 1 | 1 | 1 |
                  Other | X | 0 | 1 | 1 |
------------------------|---|---|---|---|
3                  Copy | 1 | 0 | 0 | 0 |
by value           Move | 1 | 2 | 1 | 1 |
                  Other | 0 | 0 | 1 | 1 |
------------------------|---|---|---|---|
4                  Copy | 1 | 0 | 0 | X |
Forwarding ref     Move | 0 | 1 | 0 | X |
                  Other | 0 | 0 | 1 | X |
----------------------------------------/

可能的配置:

  • 仅[#1:处理所有情况,但会临时复制
  • [#1/#2 :( B / C / D将使用#2),所以除了就地构造外,最好的结果
  • #3:处理所有情况,但要多做一些动作
  • #4:处理大多数常规情况,最佳结果
  • [#1/#2/#4:最佳结果(请注意,#4)与非常量l值完全匹配)]
  • #2/#4:最佳结果
  • #3的目的是仅写入一个重载。

    如您所见,转发参考(#4)具有最佳效果。

  • © www.soinside.com 2019 - 2024. All rights reserved.