C++ Primer 5th notes (chap 13 copy control) Object movement

1. Why do objects move

  • Using moving instead of copying objects can greatly improve performance.
  • Some resource objects that cannot be shared cannot be copied but can be moved. eg. IO class unique_ptr class

2. How to move objects

2.1 What is an rvalue?

"Lvalue is persistent; rvalue is short-lived" The lvalue has a persistent state, and the rvalue is either a literal constant or a temporary object created during expression evaluation.

2.2 Rvalue references

  • Must be bound to an rvalue reference.
  • Support mobile operation
  • Smart binding to an object to be destroyed
  • The code that uses rvalue references can freely take over the referenced object resources
int i = 42;
int &r = i;		//正确,r是i的左值引用
int &r2 = i * 42;	//错误,i*42是一个右值
const int &r3 = i * 42;	//正确,可以将一个const的引用绑定到一个右值上

int &&rr = i;	//错误,不能将一个右值引用绑定到一个左值上
int &&rr2 = i * 42;	 //正确,将rr2绑定到右值上 
int  &&rr1 = 42; 	//正确,字面常量是右值
int  &&r2 = rr1;	//错误,表达式rr1是左值

2.3 Standard library move function

The move function can be used to explicitly convert an lvalue to the corresponding rvalue reference type.

#include <utility>
int rr3 = std::move(rr1); //正确

2.4 Member functions to realize object movement

If a member function provides both copy and move versions, one version accepts an lvalue reference to const, and the second version accepts an rvalue reference to non-const.

void push_back(const X&);	  //拷贝,绑定到任意类型的X
void push_back(X&&);	//移动,只能绑定到类型X的可修改右值

inline void StrVec::push_back(const std::string& s)
{
    
    
    chk_n_alloc(); // ensure that there is room for another element
    // construct a copy of s in the element to which first_free points
    alloc.construct(first_free++, s);  
}

inline void StrVec::push_back(std::string &&s) 
{
    
    
    chk_n_alloc(); // reallocates the StrVec if necessary
	alloc.construct(first_free++, std::move(s));
}

Call example:

StrVec vec;
string s = "some string or another";
vec.push(s);//调用push(const string &)
vec.push("done");//调用push(string &&)

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/113878388