为什么要在移动构造函数中移动右值引用?
Why to move rvalue reference in a move constructor?
我遇到了以下代码:
class X {
std::vector<int> m_v;
public:
X(std::vector<int>&& v) : m_v(std::move(v)) {
};
参数 v 已经是右值引用 - 那么为什么我们需要对其应用 std::move?
简而言之:每个命名对象都是 Lvalue,即使 v
是对 Rvalue 的引用,您也需要使用 move
强制将 ctor 移动到叫做。
From reference - value categories
Even if the variable's type is rvalue reference, the expression
consisting of its name is an lvalue expression;
现在您的数据成员m_v
是包含复制和移动构造函数的向量。
接下来的句子描述了哪个叫,reference:
If both copy and move constructors are provided and no other
constructors are viable, overload resolution selects the move
constructor if the argument is an rvalue of the same type (an xvalue
such as the result of std::move or a prvalue such as a nameless
temporary (until C++17)), and selects the copy constructor if the
argument is an lvalue (named object or a function/operator returning
lvalue reference).
所以当你写:
m_v(std::move(v)) // move ctor is called because you are passing Xvalue
但是在这个:
m_v(v) // copy ctor is called because v as named object is passed
我遇到了以下代码:
class X {
std::vector<int> m_v;
public:
X(std::vector<int>&& v) : m_v(std::move(v)) {
};
参数 v 已经是右值引用 - 那么为什么我们需要对其应用 std::move?
简而言之:每个命名对象都是 Lvalue,即使 v
是对 Rvalue 的引用,您也需要使用 move
强制将 ctor 移动到叫做。
From reference - value categories
Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;
现在您的数据成员m_v
是包含复制和移动构造函数的向量。
接下来的句子描述了哪个叫,reference:
If both copy and move constructors are provided and no other constructors are viable, overload resolution selects the move constructor if the argument is an rvalue of the same type (an xvalue such as the result of std::move or a prvalue such as a nameless temporary (until C++17)), and selects the copy constructor if the argument is an lvalue (named object or a function/operator returning lvalue reference).
所以当你写:
m_v(std::move(v)) // move ctor is called because you are passing Xvalue
但是在这个:
m_v(v) // copy ctor is called because v as named object is passed