Google C + + Coding Style: rvalue reference (Rvalue Reference)

Source: Internet
Author: User

An rvalue reference is a c++11 attribute that is marked as t&&. GSG definition: Use rvalue references only for move constructors (moves constructor) and move assignment operations (move assignment). And do not use Std::forward (the perfect forwarding feature provided).

An rvalue in C + + refers to a temporary object that is no longer saved when the expression ends. In C++11, the right value is divided into the pure right value (that is, the original literal, the temporary variable generated by the expression, etc.), and a value (expiring value, used << in-depth application of the translation in c++11>>, refers to the expression related to rvalue reference, such as the returned object,t&& the function return value, etc.).

The power of an rvalue reference is not expressed as a function return value because the optimization of the compilation itself resolves unnecessary object copying operations. As a function parameter, it is also possible to avoid unnecessary copying of objects by using a form such as const t&. This is particularly useful in conjunction with standard containers, which reflect the greatest value of rvalue references: avoid deep copies.

//The following is a complete class that provides the move constructor and move assignment. #include <iostream>#include <string>#include <vector>#include <string.h>classFoo {Private:intx =0;inty =0;Char* StrPtr =nullptr; Public: Foo () {STD::cout<<"Constructor was called."<<STD:: Endl; } Foo (Const Char* s) {STD::cout<<"Constructor with string:"<< s <<STD:: Endl;if(s! =nullptr) {strPtr =New Char[strlen(s)];strcpy(strPtr, s); }    }//Copy constructorFoo (Constfoo& a): X (a.x), Y (a.y) {//Deep copyCopystringvalue (A.STRPTR);STD::cout<<"Copy constructor was called."<<STD:: Endl; }//Move constructor, no need copy string in deep.Foo (foo&& a): X (a.x), Y (A.Y), StrPtr (a.strptr) {a.strptr =nullptr;//Note to clear the previous string, this is the move.         STD::cout<<"Move constructor was called."<<STD:: Endl; } foo&operator=(Constfoo& a) {x = a.x;        y = a.y; Copystringvalue (A.STRPTR);STD::cout<<"Assignment Operator was called."<<STD:: Endl; } ~foo () {if(StrPtr! =nullptr) {STD::cout<<"Free allocated string:"<< strPtr <<STD:: Endl;DeleteSTRPTR; }STD::cout<<"Deconstructor was called."<<STD:: Endl; }Private:voidCopystringvalue (Const Char* s) {if(StrPtr! =nullptr) {DeleteSTRPTR; STRPTR =nullptr; }if(s! =nullptr) {strPtr =New Char[strlen(s)];strcpy(strPtr, s); }    }};intMainvoid) {    {STD::cout<<"need to clear string twice:"<<STD:: Endl;STD:: vector<Foo>Myvec; Foo A ("Instance A");    Myvec.push_back (a); }STD::cout<<"============"<<STD:: Endl; {STD::cout<<"only need to clear string one time:"<<STD:: Endl;STD:: vector<Foo>Myvec; Foo C ("Instance C"); Myvec.push_back (STD:: Move (c)); }STD::cout<<"============"<<STD:: Endl; {Foo D ("Instance D");    Foo x = D; }STD::cout<<"============"<<STD:: Endl; {Foo E ("Instance E"); foo&& y =STD:: Move (e); }}

By observing the number of times the code deletes a string, you can see how the Rvalue reference works. The output of the program runs as follows:

Need toClearstringTwice: Constructor  with string:Instance acopy Constructor  was called.  Free Allocated string:Instance Adeconstructor was called. Free allocatedstring: Instance Adeconstructor was called.============only need toClearstringOne time: Constructor  with string:Instance Cmove Constructor  was called. Deconstructor  was called.  Free Allocated string:Instance Cdeconstructor was called.============ Constructor  with string:Instance dcopy Constructor  was called.  Free Allocated string:Instance Ddeconstructor was called. Free allocatedstring: Instance Ddeconstructor was called.============ Constructor  with string:Instance Efree Allocatedstring: Instance Edeconstructor was called.

However, considering that reference folding in rvalue references (reference collapsing) introduces some complexity (conversion rules for left and right values), resulting in an understanding problem, the application scope of the Rvalue reference is defined as the opening point.

In practice, an rvalue reference with no directly defined type appears, called Universal Reference, which requires a type deduction. Another case is universal reference, which is defined using auto &&.

About Std::forward, it is called Perfect forwarding (Perfect Forwarding). The problem to solve is to pass parameters to another function called in the function template (go to << apply c++11>>) in the function template, exactly according to the type of the template's parameters, preserving the left and right values of the parameters, and passing the arguments to the other functions that are invoked in the functional templates. According to this definition, perfect forwarding is only for template functions that need to invoke the internal implementation, and the developer is required to identify which cases are valid and which are not. For example, the applicable scenario:

template<class T>void foo(T&& arg) {  // 如下保持arg的类型传入到bar()中  bar(std::forward<T>(arg));}

However, this scenario does not need to be forwarded if the intrinsic function does not require special handling of the left or right values. Reference: When is not the use Std::forward.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Google C + + Coding Style: rvalue reference (Rvalue Reference)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.