为什么通用参考和右值参考的流量不同
Why the difference in the flow of universal reference and rvalue reference
从高效的现代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 &&
可以同时绑定到右值和右值。
相关文章:
- C++错误消息*成员参考.**初学者*
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- 参考资源文件VC++中的$(SolutionDir)
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 具有非整数边容量的最大流量的Dinic算法
- 为什么在运算符重载时需要参考?
- 使 \page 和 \subpage 参考 doxygen 中的方法文档
- std::shared_ptr 自定义参考计数器
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- 避免在基于反向范围的for循环实现中悬挂参考
- 通用参考 l 值不复制对象
- 标准::enable_if和通用参考的使用差异
- 标准::积累参考?
- C++丢失了参考
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 矢量的通用参考
- 为什么"fun(i)"被推导出为"fun<int&>"而不是"fun<int>",因为"i"是"int"的类型而不是参考?
- C++17 和静态临时生存期的参考扩展
- C++ 参考:这两个语句有什么区别?
- 为什么通用参考和右值参考的流量不同