为什么 std::move 使用 forward_reference 而不是 lvaue 引用
why std::move takes forward_reference instead of lvaue reference
只是为了确认我对 std::move
的理解
std::move
- 将 T&
转换为 T&&
以便 T's
移动构造函数将启动(如果它存在,否则复制构造函数将发挥其作用,除非我们未从外部删除移动 ctor/assignment)。
当我查看 std::move
的可能实现时,它就像
template<typename T>
typename remove_reference<T>::type&& move(T&& param)
{
using ReturnType =typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}
它使用 remove_reference<T>
的原因是因为应用在 forward_reference T&&
上的引用崩溃
我只是想知道为什么我们需要前向引用,我们不能通过
做到这一点吗?
template<typename T>
T&& moveInQuestion(T& p){
return static_cast<T&&>(p);
}
struct someType{};
someType lvalref;
static_assert(is_same<decltype(moveInQuestion(lvalref)),decltype(std::move(lvalref))>::value,"");
static_assert
没有失败。
而且我还认为 std::move
的值类别是 lvalue
,在这种情况下 moveInQuestion
可能比 std::move
更好吗?
通常的例子是像
这样的通用代码
template<class T>
T frob() {
std::vector<T> x = /* ... */;
return std::move(x[0]);
}
对于您的 move
,当 T
是 bool
时,这会中断,因为在那种情况下 x[0]
是一个纯右值代理引用而不是左值。
只是为了确认我对 std::move
std::move
- 将 T&
转换为 T&&
以便 T's
移动构造函数将启动(如果它存在,否则复制构造函数将发挥其作用,除非我们未从外部删除移动 ctor/assignment)。
当我查看 std::move
的可能实现时,它就像
template<typename T>
typename remove_reference<T>::type&& move(T&& param)
{
using ReturnType =typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}
它使用 remove_reference<T>
的原因是因为应用在 forward_reference T&&
我只是想知道为什么我们需要前向引用,我们不能通过
做到这一点吗?template<typename T>
T&& moveInQuestion(T& p){
return static_cast<T&&>(p);
}
struct someType{};
someType lvalref;
static_assert(is_same<decltype(moveInQuestion(lvalref)),decltype(std::move(lvalref))>::value,"");
static_assert
没有失败。
而且我还认为 std::move
的值类别是 lvalue
,在这种情况下 moveInQuestion
可能比 std::move
更好吗?
通常的例子是像
这样的通用代码template<class T>
T frob() {
std::vector<T> x = /* ... */;
return std::move(x[0]);
}
对于您的 move
,当 T
是 bool
时,这会中断,因为在那种情况下 x[0]
是一个纯右值代理引用而不是左值。