gpt4 book ai didi

c++ - 当函数采用右值引用时,函数中该变量的类型是什么?

转载 作者:行者123 更新时间:2023-11-30 01:02:12 26 4
gpt4 key购买 nike

这是一个术语问题。如果我有这个:

#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 是一个右值引用,用什么术语来表示不能使用右值引用来调用采用右值引用的函数?

最佳答案

名为 v 的变量的声明类型std::vector<int>&& .此类型读作“ std::vector 的右值引用”。

名字v can 出现在 expression 中。表达式从来没有引用类型 [expr.type]/1 .但是表达式有一个 value category .当名字v出现在表达式中,如 v[0] , 子表达式 v类型为 std::vector<int>它的值类别是左值。几乎所有id-expression都是这种情况(只是一个名字的表达式)。

decltype(v)给出变量的声明类型 v .

decltype(expression)给出:

  • expression 类型的左值引用如果expression是一个左值,
  • expression 类型的右值引用如果expression是一个 xvalue,
  • expression 的类型如果expression是纯右值。

[dcl.dcl]/1 中提供了更多详细信息.

关于c++ - 当函数采用右值引用时,函数中该变量的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56602551/

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