【发布时间】:2019-06-14 17:07:31
【问题描述】:
这是一个术语问题。如果我有这个:
#include <vector>
void g(std::vector<int>&& arg);
void f0(std::vector<int>&& v) {
static_assert(std::is_same<decltype(v), std::vector<int>&&>::value); // Looks like v is an rvalue reference.
static_assert(std::is_same<decltype((v)), std::vector<int>&>::value);
static_assert(std::is_same<std::decay<decltype(v)>::type, std::vector<int>>::value);
return g(std::move(v)); // Fine.
}
那么v 是什么类型?如果您正在谈论调用f0,您会说“f0 采用右值引用”(对吗?)但在f0 内,v 不是右值引用,否则std::move 不会不需要?正确的?但是static_assert 表明它是一个右值,对吧?
同样:
void f1(std::vector<int>&& v) {
static_assert(std::is_same<decltype(v), std::vector<int>&&>::value);
static_assert(std::is_same<decltype((v)), std::vector<int>&>::value);
static_assert(std::is_same<std::decay<decltype(v)>::type, std::vector<int>>::value);
return g(v); // Error: cannot bind rvalue reference of type 'std::vector<int>&&' to lvalue of type 'std::vector<int>'.
// So is v just a std::vector<int>?
}
本地右值引用的行为方式相同:
void f2(std::vector<int>&& v) {
std::vector<int>&& vv = std::move(v);
static_assert(std::is_same<decltype(vv), decltype(v)>::value, "They are the same decltype. So being an argument isn't magic.");
static_assert(std::is_same<decltype(vv), std::vector<int>&&>::value);
static_assert(std::is_same<decltype((vv)), std::vector<int>&>::value);
static_assert(std::is_same<std::decay<decltype(vv)>::type, std::vector<int>>::value);
return g(vv); // Error: cannot bind rvalue reference of type 'std::vector<int>&&' to lvalue of type 'std::vector<int>'
}
描述v 类型的正确术语是什么?说f0 采用右值引用是否正确?如果v 是右值引用,那么用什么术语说右值引用不能用于调用采用右值引用的函数?
【问题讨论】:
-
基本上,命名的右值引用(类型)是左值(值类别)。
标签: c++ rvalue-reference lvalue-to-rvalue