gpt4 book ai didi

c++ - 转发引用不是被推导出为 r 值引用吗?

转载 作者:行者123 更新时间:2023-12-03 19:39:50 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Rvalue Reference is Treated as an Lvalue?

(4 个回答)


去年关闭。




我有一个关于转发引用的具体问题。 (我认为)我了解 r 值引用和 std::move ,但我无法理解转发引用:

#include <iostream>
#include <utility>

template <typename T> class TD; // from "Effective Modern C++"

void consume(const int &i) { std::cout << "lvalue\n"; }
void consume(int &&i) { std::cout << "rvalue\n"; }

template <typename T>
void foo(T&& x) {
// TD<decltype(x)> xType; - prints int&&
consume(x);
}

int main() {
foo(1 + 2);
}
Tint , 没关系。如果 xint&& 类型,为什么它打印“左值”,我们需要 std::forward ?我的意思是, int&& 的转换在哪里?至 const int&这里?

最佳答案

类型和 value categories是表达式的两个独立属性。

Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category. Each expression has some non-reference type, and each expression belongs to exactly one of the three primary value categories: prvalue, xvalue, and lvalue.

x的类型是 int&& , 但是 x是变量的名称, x是一个左值表达式本身,它不能绑定(bind)到 int&& (但可以绑定(bind)到 const int& )。
(强调我的)

The following expressions are lvalue expressions:

  • the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;

这意味着当函数同时具有左值引用和 rvalue-reference 时重载,值类别在 overload resolution 中考虑也。

More importantly, when a function has both rvalue reference and lvalue reference overloads, the rvalue reference overload binds to rvalues (including both prvalues and xvalues), while the lvalue reference overload binds to lvalues:


If any parameter has reference type, reference binding is accounted for at this step: if an rvalue argument corresponds to non-const lvalue reference parameter or an lvalue argument corresponds to rvalue reference parameter, the function is not viable.

std::forward用于转换为右值或左值,与转发引用参数的原始值类别一致。当左值 int传递给 foo , T推导出为 int& ,然后 std::forward<T>(x)将是一个左值表达式;当右值 int传递给 foo , T推导出为 int ,然后 std::forward<T>(x)将是一个右值表达式。所以 std::forward可用于保留原始转发引用参数的值类别。作为对比 std::move总是将参数转换为右值表达式。

关于c++ - 转发引用不是被推导出为 r 值引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66567553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com