🐭 现代 C++ 的值类型扩展

随着 C++ 标准的演进,C++ 中的值类型也在演进,值类型的演进是为了配合实现新的特性。比如,右值引用,移动语义,完美转发,拷贝消除等都是提升性能的新特性,都需要右值以及右值引用来配合。
现代 C++ 中的值类型:
这里不给出它们的完整定义,它们只是在特定的场景下才有意义:
代码示例 :

  1. #include <string>
  2. struct X {
  3. int n;
  4. };
  5. extern X x;
  6. int main(void) {
  7. // prvalues perform initialization
  8. // glvalues produce locations
  9. X{4}; // prvalue: represents initialization of an X object
  10. x.n; // glvalue: represents the location of x's member n
  11. X{4}.n; // glvalue: represents the location of X{4}'s member n;
  12. // in particular, xvalue, as member is expiring
  13. using T = X[2];
  14. T{{5}, {6}}; // prvalue: represents initialization of an array of 2 X's
  15. T{{5}, {6}}[0]; // xvalue: represents location of expiring array element
  16. // what is a memory location?
  17. // an object of scalar type (arithmetic type, pointer type, enumeration type, or
  18. // std::nullptr_t), or the largest contiguous sequence of bit fields of non-zero length
  19. struct S {
  20. char a; // memory location #1
  21. int b : 5; // memory location #2
  22. int c : 11, // memory location #2 (continued)
  23. : 0, // not a memory location
  24. d : 8; // memory location #3
  25. int e; // memory location #4
  26. double f; // memory location #5
  27. std::string g; // several memory locations
  28. };
  29. return 0;
  30. }

:::tips

  1. 右值概念的扩展很有意义,比如右值引用就是连接移动语义与完美转发的胶水
  2. glvalue, prvalue 概念的扩展,就是实现拷贝消除的基础
  3. 注意理解内存地址 (位置) 的概念,初始化物的概念比较好理解 :::

    🐂 std::move 与 std::forward 的本质

    std::move 与 std::forward 的 clang++ 实现:
    代码示例 : ```cpp //type_traits from clang++ template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR typename remove_reference<_Tp>::type&& move(_Tp&& t) _NOEXCEPT { typedef _LIBCPP_NODEBUG_TYPE typename remove_reference<_Tp>::type _Up; return static_cast<_Up&&>(t); }

template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR _Tp&& forward(typename remove_reference<_Tp>::type& t) _NOEXCEPT { return static_cast<_Tp&&>(t); }

template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR _Tp&& forward(typename remove_reference<_Tp>::type&& t) _NOEXCEPT { static_assert(!is_lvalue_reference<_Tp>::value, “can not forward an rvalue as an lvalue”); return static_cast<_Tp&&>(t); } ``` 从上面的 clang++ 实现可以看出,它们本质上都是类型转换,有点「名不副实」的意思:
std::move:
无条件的将一个值转换为右值,使得这个值准备好了「可以被移走」,本质是类型转换,并没有移动什么东西
std::forward:
将一个值的类型在接下来的参数传递过程中维持原始类型不变,本质也是类型转换,并没有转发什么东西

std::move 与 std::forward 对移动语义来说只是第一阶段的配合:
std::move 只是表达了程序员的一种意愿,无条件的将一个值转换为右值,为接下来的对象移动操作做好了准备,仅此而已,并不关心这接下来的移动操作是否能完成。
std::forward 只是确保参数的类型在传递过程中维持不变,就像个万能的邮差,仅此而已,也不关心这接下来的移动操作是否能完成。

不要试图移动 const 对象:
std_move_const.png

🐯 总结

  1. std::move 与 std::forward 都只是类型转换操作而已
  2. 它们就是一些 C++ 规则的语言表示形式,它们都是编译时行为,和运行时没有任何关系