Reading notes effective C + + Item 26 Try to postpone the definition of a variable

Source: Internet
Author: User

1. Defining variables can cause construction and destruction overhead

Whenever you define a variable of a type: when the control flow reaches the defined point of the variable, you introduce the overhead of calling the constructor, and when you leave the scope of the variable, you introduce the overhead of calling the destructor. There is also a cost to unused variables, so avoid this definition as much as possible.

2. The variable definitions in the normal function postpone the example of a 2.1 variable that might not be used

You may think that you will never define unused variables, and you may want to consider them again. Looking at the following function, this function returns the encrypted version of password, which provides a password that needs to be long enough. If the password is too short, the function throws an exception of type Logic_error, which is defined in the standard C + + library (Item 54):

1 //This function defines the variable "encrypted" too soon2 3STD::stringEncryptpassword (ConstSTD::string&password)4 5 {6 7 using namespacestd;8 9 stringencrypted;Ten  One if(Password.length () <minimumpasswordlength) { A  - ThrowLogic_error ("Password is too short"); -  the } -  -...//Do whatever is necessary -  + //encrypted version of password in encrypted -  + returnencrypted; A  at}

The object encrypted is not completely used, but it is definitely not used if an exception is thrown. This means that if Encryptpassword throws an exception, you won't use encrypted, but you'll also pay for encrypted's constructors and destructors. Therefore, it is best to postpone the definition of encrypted until you think you will use it:

1 //This function postpones encrypted ' s definition until it's truly necessary2 3STD::stringEncryptpassword (ConstSTD::string&password)4 5 {6 7 using namespacestd;8 9 if(Password.length () <minimumpasswordlength) {Ten  One ThrowLogic_error ("Password is too short"); A  - } -  the stringencrypted; -  -...//Do whatever is necessary -  + //encrypted version of password in encrypted -  + returnencrypted; A  at}

2.2 One way to postpone variable definition

The above code does not appear to be compact enough because the encrypted definition does not have any initialization parameters. It also means that the default constructor is called. In many cases, the first thing you do to an object is to give it some value, which is usually done by assigning values. Item 4 explains why constructing an object by default is less efficient than initializing it with a value . The analysis is equally applicable here. For example, suppose the most difficult part of the Encryptpassword function is executed in the following function:

1 void Encrypt (std::string//  encrypts s in place

The Encryptpassword can then be implemented as follows, although this may not be the best approach:

1 //This function postpones encrypted ' s definition until2 3 //it ' s necessary, but it's still needlessly inefficient4 5STD::stringEncryptpassword (ConstSTD::string&password)6 7 {8 9...//Import STD and check length as aboveTen  One stringEncrypted//Default-construct Encrypted A  -encrypted = password;//Assign to encrypted -  the Encrypt (encrypted); -  - returnencrypted; -  +}

2.2 Better ways to postpone variable definitions

A better approach is to initialize encypted with password, which skips meaningless and potentially expensive default constructors:

1 //Finally, the best define and initialize encrypted2 3STD::stringEncryptpassword (ConstSTD::string&password)4 5 {6 7...//Import STD and check length8 9 stringencrypted (password);//define and initialize via copyTen  One //Constructor A  - Encrypt (encrypted); -  the returnencrypted; -  -}

2.3 Deferred variable definition the true meaning

This proposal is the true meaning of "postponing as much as possible" in the title of this article. not only will you postpone the definition of the variable until you have to use it, you should also try to postpone the definition until you get the initialization value of the variable . By doing so, you can avoid unnecessary constructs and destructors, and avoid unnecessary default constructors. And, by initializing the variable in a context that has a clear meaning, you also help to indicate the intent to use the variable .

3. How to handle variable definitions in loops

It's time for you to think: What's the loop going to do with it? If a variable is used only in a loop, is the variable defined in the loop, and each iteration of the loop is assigned a good value? Or is it better to define it inside the loop? Which is the following structure which is good?

1 //approach A:define outside Loop2 3 Widget W;4 5  for(inti =0; I < n; ++i) {6 7W =some value dependent on I;8 9 ... Ten  One }  A  -  -  the //approach b:define inside Loop -  -  for(inti =0; I < n; ++i) { -  + Widget W (some value dependent oni); -  + ... A  at}

Here I replace the object of type string with a widget-type object to avoid any prejudice to the overhead of executing constructors, destructors, or assignment operators.

For widgets, the cost of both methods is as follows:

    • Method One: 1 constructors + 1 destructors +n assignment operations
    • Method Two: N Constructors and N destructors

If the cost of an assignment operation is smaller than a pair of constructors/destructors, method A is more efficient. Especially when n is very big. Otherwise, method B is more efficient. And method A makes the variable w visible in a larger range than method B, which violates the program's understanding and operability. Therefore, unless you encounter the following two points: (1) The assignment is less than the construction/destruction overhead (2) you are dealing with performance-sensitive code. Otherwise you should use method B by default.

Reading notes effective C + + Item 26 Try to postpone the definition of a variable

Related Article

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.