我正在尝试std::move
和std::forward
的不同之处,我发现我无法在类字段上使用std :: forward:
name = std::forward<T>(rhs.name);
下面是完整的例子。我在gcc 6.3下得到的错误是:
C:/PROGRA~1/MINGW-~1/X86_64~3.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/6.3.0/include/c++/bits/move.h:89:7: error: static assertion failed: template argument substituting _Tp is an lvalue reference type
static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument"
^~~~~~~~~~~~~
我理解原因可能是因为T
属于WrongUseOfMove
类型。但我想知道是否只能转发子变量。例如,我可以使用rhs
参数传递并将其字段转发给不同的类变量。
#include <iostream>
#include <string>
#include <vector>
class WrongUseOfMove {
public:
template<typename T>
WrongUseOfMove(T&& rhs)
{
//name = std::move(rhs.name); // Very wrong!!
//name = std::forward<T>(rhs.name); // Does not compile, T is WrongUseOfMove instead decltype(rhs.name);
name = std::forward<decltype(rhs.name)>(rhs.name); // compiles - but is it correct?
std::cout << __PRETTY_FUNCTION__ << "\n";
}
WrongUseOfMove(){}
std::string name;
};
int main()
{
WrongUseOfMove wm;
WrongUseOfMove wm2 = wm;
}