[英]Why an Rvalue Reference is Turned into Lvalue Reference by a Universal Reference
[英]Why the difference in the flow of universal reference and rvalue reference
使用Efficient Modern C ++,第25项。我们有一个例子
class Widget {
public:
template<typename T>
void setName(T&& newName)
{ name = std::forward<T>(newName); }
...
};
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*
构造const char*
将引用绑定到该std::string
。
请注意,虽然rvalue引用(如std::string &&
只能绑定到rvalue,但模板化的等效T &&
可能会绑定到rvalues和lvalues。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.