🐭 现代 C++ 的值类型扩展
随着 C++ 标准的演进,C++ 中的值类型也在演进,值类型的演进是为了配合实现新的特性。比如,右值引用,移动语义,完美转发,拷贝消除等都是提升性能的新特性,都需要右值以及右值引用来配合。
现代 C++ 中的值类型:
这里不给出它们的完整定义,它们只是在特定的场景下才有意义:
代码示例 :
#include <string>struct X {int n;};extern X x;int main(void) {// prvalues perform initialization// glvalues produce locationsX{4}; // prvalue: represents initialization of an X objectx.n; // glvalue: represents the location of x's member nX{4}.n; // glvalue: represents the location of X{4}'s member n;// in particular, xvalue, as member is expiringusing T = X[2];T{{5}, {6}}; // prvalue: represents initialization of an array of 2 X'sT{{5}, {6}}[0]; // xvalue: represents location of expiring array element// what is a memory location?// an object of scalar type (arithmetic type, pointer type, enumeration type, or// std::nullptr_t), or the largest contiguous sequence of bit fields of non-zero lengthstruct S {char a; // memory location #1int b : 5; // memory location #2int c : 11, // memory location #2 (continued): 0, // not a memory locationd : 8; // memory location #3int e; // memory location #4double f; // memory location #5std::string g; // several memory locations};return 0;}
:::tips
- 右值概念的扩展很有意义,比如右值引用就是连接移动语义与完美转发的胶水
- glvalue, prvalue 概念的扩展,就是实现拷贝消除的基础
- 注意理解内存地址 (位置) 的概念,初始化物的概念比较好理解
:::
🐂 std::move 与 std::forward 的本质
std::move 与 std::forward 的 clang++ 实现:
代码示例 : ```cpp //type_traits from clang++ templateinline _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
template
std::move:
无条件的将一个值转换为右值,使得这个值准备好了「可以被移走」,本质是类型转换,并没有移动什么东西
std::forward:
将一个值的类型在接下来的参数传递过程中维持原始类型不变,本质也是类型转换,并没有转发什么东西
std::move 与 std::forward 对移动语义来说只是第一阶段的配合:
std::move 只是表达了程序员的一种意愿,无条件的将一个值转换为右值,为接下来的对象移动操作做好了准备,仅此而已,并不关心这接下来的移动操作是否能完成。
std::forward 只是确保参数的类型在传递过程中维持不变,就像个万能的邮差,仅此而已,也不关心这接下来的移动操作是否能完成。
🐯 总结
- std::move 与 std::forward 都只是类型转换操作而已
- 它们就是一些 C++ 规则的语言表示形式,它们都是编译时行为,和运行时没有任何关系
