c++ - 为什么 std::move 使用 std::remove_reference?

标签 c++ c++11 c++14 move

根据 http://en.cppreference.com/w/cpp/utility/move

std::move声明如下:

template <typename T>
std::remove_reference<T>::type&& move(T&& t);

据我了解,当代码被模板化时,扣除Ttypename T丢失有关引用的信息,因此如下:

template <typename T>
void someFunction(T&& value);

像这样使用时:

int five=5;
someFunction(five);

然后

  • value类型为 int&
  • Tint

const float value = 5.25;
someFunction(value);

然后

  • value类型为 const float&
  • Tconst float .

如果是这样,那么在 move 声明中就没有必要将返回类型声明为: std::remove_reference<T>::type&& , 因为 T 已经不是引用了。

此外,如果std::move将引用作为参数(实际上是左值引用),然后返回 static_cast<T&&>(t)std::move事实上,由于引用折叠将返回左值引用或右值引用,因此它的行为更像 std::forward。不动。那么什么是技巧,使它正常工作,我不明白?

最佳答案

您的示例不正确:

int five=5;
someFunction(five);

在这种情况下,T 被推断为 int&,而不是 int。第二个例子也是如此; T 推导为 const int&

因此,仅返回 T&& 意味着 T&& &,由于引用折叠规则,它是 T&

这就是为什么需要 std::remove_reference 的原因,以确保该类型上没有引用以防止发生引用折叠。

关于c++ - 为什么 std::move 使用 std::remove_reference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266472/

相关文章:

c++ - Windows 中崩溃进程的可预测退出代码

c++ - C++ 中 BigInt 类的良好和基本实现

c++ - 是依靠GCC/LLVM的 `-fexceptions`技术上未定义的行为吗?

c++ - 多类型STL映射

c++ - 在 C++ 中实现通用构建器模式

c++ - 使用 (c++11) 声明类型时将 __declspec(dllimport) 关键字放在哪里

c++ - 我的 kbhit() 在 Mac 上不工作,制作乒乓球游戏

c++ - 多次调用 QTcpSocket::write?

c++ - sf::RenderWIndows的 vector

c++ - 为什么自动不检测函数的引用类型