【问题标题】:Why forwarding reference does not work?为什么转发参考不起作用?
【发布时间】:2016-06-27 13:47:23
【问题描述】:

我对这段代码有疑问:

#include <string>
#include <iostream>

struct A{
    template<class UT>
    A(UT &&s) : internal(std::forward<std::string>(s)){

    }

    std::string internal;
};

int main(){
    const std::string &s = "hello";

    A a1{ s };

    std::cout << "s = " << s << std::endl;
}

当前的示例无法编译,如果我将 s 更改为非常量,它会移动字符串。

我有类似的代码可以正常工作,但在这种情况下,我看不到有什么问题。

【问题讨论】:

  • “通用参考”一词不再适用于这个概念,因为它用词不当。甚至该术语的发明者也否认了它,而是更喜欢“转发引用”。
  • 使用std::forward&lt;UT&gt;(s),它仍然不会像现在一样移动字符串,但至少它可以编译并正确处理其他情况
  • @PiotrSkotnicki - 是的。我太傻了:D
  • @PiotrSkotnicki:它不应该移动字符串。您不能从 const&amp; 移动。
  • @NicolBolas 再次阅读,我说 “它仍然不会像现在一样移动字符串”

标签: c++11 forwarding-reference


【解决方案1】:

您错误地使用了转发引用。你没有给std::forward 目标类型。你给它推导出来的模板:

A(UT &&s) : internal(std::forward<UT>(s)){

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-11
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多