定义 ,需要理解三个方面的概念才有可能完全掌握。
std::move : https://en.cppreference.com/w/cpp/utility/move
static cast : https://en.cppreference.com/w/cpp/language/static_cast
value_category:https://en.cppreference.com/w/cpp/language/value_category
表达式的值类型。
每个C++表达式(带操作数的运算符、文字、变量名等)都有两个独立的属性:类型和值类别。每个表达式都有一些非引用类型,并且每个表达式恰好属于三个主要值类别之一:prvalue、xvalue和lvalue。
std::move的实现是将类型static_cast为右值引用。
std::move is used to indicate that an object t may be “moved from”, i.e. allowing the efficient transfer of resources from t to another object.
In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.
https://mp.weixin.qq.com/s/_9-0iNUw6KHTF3a-vSMCmg
https://zhuanlan.zhihu.com/p/374392832
理解std::move核心在于理解static_cast .
再往下一层在于理解xvalue和其生命周期。
(1)static_cast的语法如下:
static_cast < new-type > ( expression )
(2)static_cast右值引用会得到xvalue
If new-type is an rvalue reference type, static_cast converts the value of glvalue, class prvalue, or array prvalue (until C++17)any lvalue (since C++17) expression to xvalue referring to the same object as the expression, or to its base sub-object (depending on new-type). If the target type is an inaccessible or ambiguous base of the type of the expression, the program is ill-formed. If the expression is a bit-field lvalue, it is first converted to prvalue of the underlying type. This type of static_cast is used to implement move semantics in std::move.
(3)xvalue是资源可重用对象
an xvalue (an “eXpiring” value) is a glvalue that denotes an object whose resources can be reused;
a function call or an overloaded operator expression, whose return type is rvalue reference to object, such as std::move(x);
(4)xvalue是rvalue,可以通过初始化const引用和右值引用延长生命周期
An rvalue may be used to initialize an rvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
An rvalue may be used to initialize a const lvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
(5) http://thbecker.net/articles/rvalue_references/section_01.html
每一类值对应不同的构造方法:
prvalue初始化glvalue,是直接构建,不用调用拷贝或移动构造函数;
xvalue初始化lvalue,会调用移动函数,也就是move;
lvalue初始化lvalue,会调用拷贝构造函数。
它们三者与move的关系是:
xvalue可以被直接move;
prvalue被move的时候,可以理解生成了一个临时变量xvalue,这个临时变量xvalue被move了;
如果move lvalue,那么需要使用std::move将lvalue变成xvalue,从而move生成后的xvalue。
c++的move全靠程序员自己根据语言提供的特性来实现,比如字符串类里面有个c str,你得自己实现移动构造函数,还得自己处理原字符串的状态,防止它在之后调用析构函数的时候破坏新字符串
上一篇:常用成语全集
下一篇:彩霞满天是古诗里的吗