【发布时间】:2017-01-04 07:11:58
【问题描述】:
这是VS2015中的一些代码:
class Elem
{
public:
Elem(int i) : a(i) {}
Elem(Elem && other) = default;
Elem(const Elem & other) = default;
private:
int a;
};
int main()
{
std::vector<Elem> vv;
// case 0
vv.push_back(Elem{ 0 }); // call push_back(Elem &&);
// case 1
Elem e1{ 1 };
vv.push_back(e1); // call push_back(const Elem &);
// case 2
Elem e2{ 2 };
auto & lref = e2;
vv.push_back(lref); // call push_back(const Elem &);
// case 3
Elem e3{ 3 };
auto && rref = std::move(e3);
vv.push_back(rref); // call push_back(const Elem &);
// case 4
Elem e4{ 4 };
vv.push_back(std::move(e4)); // call push_back(Elem &&);
return 0;
}
情况3,rref的类型为右值引用,其值类别为lvalue,调用push_back(const Elem &)。
在案例 4 中,根据 Effective Modern C++ Item 23,std::move 的实现类似于
// C++ 14
template<typename T>
decltype(auto) move(T&& param)
{
using ReturnType = remove_reference_t<T>&&;
return static_cast<ReturnType>(param);
}
std::move(e4)的类型为Elem &&,其值类别为prvalue,调用push_back(Elem &&)。
所以T&& 的lvalue 匹配const T &,T&& 的prvalue 匹配T&&,表达式的类型和值类别在T 之间的重载解析期间实际上做了什么, const T & 和 T &&?
很抱歉没有清楚地描述我的问题。正如很多链接所说,如果参数的值类别是prvalue,则将调用T&& 的函数;值类别为lvalue,将调用const T & 的函数。
我可以简单地说参数的类型用于重载解析,而当参数的类型是引用时检查值类别的引用绑定?
【问题讨论】:
-
一旦你的变量有了名字,它就是一个左值
标签: c++ c++11 move rvalue-reference