C++11 features are used extensively in stout, and c++11 move and forward are probably the most magical features.
- Differences between left and right values
int 0; // A is an lvalue, 0 is the right value int b = rand (); // B is the Lvalue, rand () is the right value
Intuitive understanding: Left value on the left side of the equals sign, right value on the right side
In-depth understanding: The Lvalue has a name, can get its memory address according to the left value, and the right value has no name, cannot get the address according to the right value.
2. Referencing overlay rules
Lvalue references a& and rvalue references a&& can overlay each other
a& + a& = a&a& + a&& = a&a&& + a& = a&a&& Amp + a&& = a&&
For example, void foo (t&& x), if T is Int&, X is lvalue semantics, if T is Int&&, and X is rvalue semantics
3. Why Use Std::move
If Class X contains a pointer to a resource, under Lvalue semantics, the assignment constructor for class X is as follows:
X::X (const x& other ) { // .... // Destroying Resources // Copy the other resource and point the pointer to it // ...}
The application code is as follows, where TMP is assigned to a and is no longer used.
X tmp; // ... After a series of initialization ... X a = tmp;
As above, the execution is performed in chronological order as follows: first executes the default constructor (TMP request Resource), executes the copy constructor once (a copy resource), and then executes the destructor once the scope is exited (TMP frees the Resource). Since the TMP will be destroyed sooner or later, in the execution of the copy constructor, a can the TMP resources "steal", directly for me to use?
X::X (const x& other ) { // Exchange Resources for this and other}
This reduces the creation and release of resources at a time. This is what std::move is going to achieve.
4. Implementation of Std::move
The std::move is used to force the conversion of an lvalue to a right value. It is implemented in the following ways:
template<class t> typename remove_reference<T>::type&&std::move (T && a) noexcept{ typedef typename Remove_reference<T>::type&& rvalref; return static_cast<rvalref>(a);}
When a is an int lvalue (rvalue), based on the reference overlay principle, T is int&, remove_reference<t> = int, std::move return type is Int&&, or rvalue reference
5. Use of Std::move
#include <utility>#include<iostream>#include<string>#include<vector>voidFooConstSTD::string&N) {std::cout<<"Lvalue"<<Std::endl;} voidFoo (std::string&&N) {std::cout<<"rvalue"<<Std::endl;} voidBar () {foo ("Hello");//rvalueSTD::stringA =" World"; Foo (a); //LvalueFoo (Std::move (a));//rvalue}intMain () {std::vector<STD::string> A = {"Hello"," World"}; Std::vector<STD::string>b; B.push_back ("Hello"); B.push_back (Std::move (a[1])); Std::cout<<"bsize:"<< b.size () <<Std::endl; for(std::string&x:b) Std::cout<< x <<Std::endl; Bar (); return 0;}
Stout Code Analysis Ten: C++11 's move and forward