C++: Quote and Move Voice

1. Quote:

References can be understood as aliases for variables. (The variables mentioned here include not only defined local variables, global variables, etc., but also temporary variables and intermediate variables used in the program)

Mentioning references requires mentioning the probability of lvalues ​​and rvalues, which is also a classification of variables.

lvalue and rvalue:

As the name implies, the variable that can be placed on the left side of the equal sign is called an lvalue. The definition in the book is a quantity whose address can be obtained. Personally, I think this definition is inappropriate (a constant can take an address). Specifically, it should be a named quantity or object that can be assigned on the left side of the equal sign. The definition of rvalue given in the book is all quantities other than lvalues, more precisely, literal constants, temporary values, temporary objects, and anonymous objects.

 

Understand lvalue and rvalue, and introduce, lvalue reference and rvalue reference.

An lvalue reference is a reference to an lvalue. The symbol & and an lvalue reference can be understood as an alias of an lvalue. Unlike a pointer, it does not need to allocate memory. The modification of the reference is the modification of the variable.

The "*" operation of a pointer is called dereference, and the difference between pointer dereference and reference is the difference between pointer and reference. The two are fundamentally different. The process of pointer dereferencing is also the process of obtaining a variable reference by a pointer, so this operation can also be called fetching content.

The rvalue reference is to take a reference to the rvalue, the symbol &&, the principle is to take over the memory address of the rvalue, to avoid the release of the rvalue (temporary object, temporary variable, anonymous object), the deep reason is to prevent caused by parameter assignment. The extra overhead and waste of resources (memory, CPU) can also avoid shallow copying of class types.

 

2. Move Voice:

The move voice is a concept based on rvalue references. The idea of ​​moving voice and rvalue reference is basically the same, preventing extra overhead and program errors caused by copying. For the copying of some objects, if you do not write a separate copy constructor or overload the assignment operator, you may not be able to deep copy (deep copy), and shallow copy (shallow copy) will cause program operation errors. So you need to write a move constructor or overload the move assignment operator, both of which are better than copy constructors and overloaded assignment operations. Move operation statement in C++ std::move();

 

Since rvalue references are supported by the C++11 standard, both rvalue references and move semantics are C++11 stuff.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325562944&siteId=291194637