为什么通用参考和右值参考的流量不同

Why the difference in the flow of universal reference and rvalue reference

本文关键字:参考 流量 值参 为什么      更新时间:2023-10-16

从高效的现代C++工作,第 25 项。 我们有一个例子。

案例1

class Widget {
public:
template<typename T>
void setName(T&& newName)
{ name = std::forward<T>(newName); }
...
};

案例2

class Widget {
public:
void setName(const std::string& newName)
{ name = newName; }
void setName(std::string&& newName)
{ name = std::move(newName); }
...
};

电话会议

Widget w;
w.setName("Adela Novak");

现在假设情况 1,本书指出文本被传达给 w 名称数据成员中的 t std::string 的赋值运算符。

假设情况 2,本书指出 ->首先从文字创建一个临时,调用字符串构造函数,因此 setName 参数可以绑定到它,并且比这个临时移动到 w 的名称数据成员中。

问题

为什么会出现这种行为差异,我该如何思考?

也就是说,为什么在案例 1 中不需要临时?为什么会有区别?T&& 是否不被推导出为对字符串的右值引用,从而得出与案例 2 相同的行为(显然不是,根据书中,但为什么(?

在情况 1 中,T被推导出为 const char (&)[12] ,而不是 std::string 。编译器尚无理由将字符串文本提升为std::string。在情况 2 中,每个重载都需要引用一个std::string,这会强制创建一个临时std::string,可以使用隐式const char*构造函数绑定引用。

请注意,虽然右值引用(如 std::string &&(只能绑定到右值,但模板化等效T &&可以同时绑定到右值和右值。