Normally r-values have expression scope, meaning the values are destroyed at the end of the expression in which they are created.
std::cout << 2 + 3; // 2 + 3 evaluates to r-value 5, which is destroyed at the end of this statement
However, when a reference to a const value is initialized with an r-value, the lifetime of the r-value is extended to match the lifetime of the reference.
int somefcn() { const int &ref = 2 + 3; // normally the result of 2+3 has expression scope // and is destroyed at the end of this statement // but because the result is now bound to a reference to a const value... std::cout << ref; // we can use it here } // and the lifetime of the r-value is extended to here, // when the const reference dies
However, if we construct an object or do an assignment where the argument is an r-value, then we know that r-value is just a temporary object of some kind. Instead of copying it (which can be expensive), we can simply transfer its resources (which is cheap) to the object we’re constructing or assigning. This is safe to do because the temporary will be destroyed at the end of the expression anyway, so we know it will never be used again!
深拷贝解决浅拷贝的问题,移动复制解决深拷贝的问题。
The && means "rvalue reference" and is a reference to which we can bind an rvalue. The word "rvalue" is intended to complement "lvalue," which roughly means "something that can appear on the left-hand side of an assignment." So an rvalue is – to a first approximation – a value that you can’t assign to, such as an integer returned by a function call. Thus, an rvalue reference is a reference to something that nobody else can assign to, so we can safely "steal" its value.
&&的意思是“右值引用”,是一个我们可以绑定右值的引用。“rvalue”这个词是对“lvalue”的补充,它大致意思是“可以出现在赋值左侧的某个值”。因此,rvalue是——对于第一个近似值——一个不能赋值的值,例如函数调用返回的整数。因此,右值引用是对其他人无法分配的对象的引用,因此我们可以安全地“窃取”它的值。
a move constructor allows an object to move simply and cheaply from one scope to another.
That way, objects that we cannot or would not want to copy out of a scope can be simply and cheaply moved out instead.