为什么我的代码打印右值 2 次而不是右值和左值?

Why is my code printing rvalue 2 times instead of rvalue & lvalue?

本文关键字:我的 代码 打印 为什么      更新时间:2023-10-16

所以我想练习std::forward的用法,并创建了一个具有 2 个构造函数的Test类。 一个带有T&,另一个带有T&&作为重载。T&打印左值T&&打印右值,所以我知道正在使用哪个构造函数。我在堆栈上创建了 2 个类实例,令我惊讶的是,这两个实例都使用了T&&重载。

#include <iostream>
#include <type_traits>
#include <utility>
template <class T> auto forward(T &&t) {
if constexpr (std::is_lvalue_reference<T>::value) {
return t;
}
return std::move(t);
}
template <class T> class Test {
public:
Test(T &) { std::cout << "lvalue" << std::endl; };
Test(T &&) { std::cout << "rvalue" << std::endl; };
};
int main() {
int x = 5;
Test<int> a(forward(3));
Test<int> b(forward(x));
return 0;
}

我尝试使用原始的std::forward函数并实现它,但两次它都打印了rvaluex2。我做错了什么?

您的问题源于返回类型forward。 您使用auto作为返回类型,这不会为您推断出引用。 这意味着当你返回时,无论它从哪个分支返回,你都按值返回,这意味着你有一个 prvalue。

您需要的是decltype(auto),以便返回右值或左值引用,具体取决于 return 语句。 用

template <class T> decltype(auto) forward(T &&t) {
if constexpr (std::is_lvalue_reference<T>::value)
return t;
else
return std::move(t);
}

为您提供输出:

rvalue
lvalue
相关文章: