C + + Programming practical skills #32: As much as possible to postpone the definition of variables __linux

Source: Internet
Author: User
Yes, we agree with the requirement that variables in C should be defined in the head of a module, but in C + +, it's not necessary, unnatural, and expensive to cancel this practice.

Do you remember. If you define a variable of a type that has constructors and destructors, when the program runs to the definition of the variable, it inevitably faces the cost of the construct, and the cost of the destructor when the variable leaves its life space. This means that defining useless variables is necessarily accompanied by unnecessary overhead, so avoid this if possible.

As I know, your programming style is elegant and sophisticated. So you might be thinking that you never define a useless variable, so this tip doesn't apply to your rigorous and compact programming style. But don't worry, look at this function: When the password is long enough, it returns an encrypted version of the password; When the password is too short, the function throws the Logic_error type exception (the Logic_error type is defined in the C + + standard library, see tip 49):

This function too early defines the variable "encrypted"
string encryptpassword (const string& password)
{
  string encrypted;
  if (Password.length () < Minimum_password_length) {
     throw logic_error ("Password is too short");
  Carry out the necessary operation and put the encrypted version of the password  
  into the encrypted;
  return encrypted;
}

Object encrypted is not completely useless in a function, but it is useless if an exception is thrown. However, even if Encryptpassword throws an exception (see Trick M15), the program also has to bear the overhead of encrypted construction and destructor. So it's a good idea to postpone encrypted until you really need it:

This function defers the definition of encrypted
//until it is really needed to define
string Encryptpassword (const string& password)
{
  if ( Password.length () < Minimum_password_length) {
    throw logic_error ("Password is too short");
  string encrypted;
  Carry out the necessary operation and put the encrypted version of the password  
  into the encrypted;
  return encrypted;
}

This code is not so rigorous because the encrypted definition does not take any initialization parameters. This will cause its default constructor to be invoked. In most cases, the first thing to do with an object is to give it a value, which is usually done by assigning values. Tip 12 explains why it's much less efficient to "construct an object by default and then assign it to it" than "initialize the object with the value you really want". This assertion applies in the same way. For example, suppose the most difficult part of Encryptpassword is in this function:

void Encrypt (string& s);      S encrypt here

So Encryptpassword can be implemented like this (of course, it's not the best way to implement it):

This function defers the definition of encrypted
//until it is needed, but it is still very inefficient
string Encryptpassword (const string& password)
{
  ...                      //ibid., check length
  string encrypted;        Default construction encrypted
  encrypted = password;    Assigning value
  Encrypt (encrypted) to encrypted;
  return encrypted;
}

A better approach is to initialize the encrypted with password, bypassing unnecessary calls to the default constructor:

The best way to define and initialize encrypted
string encryptpassword (const string& password)
{
  ...                             Check length
  string encrypted (password);     The
  Encrypt (encrypted) is defined and initialized by a copy constructor;
  return encrypted;
}

This code illustrates the true meaning of the three words "as much as possible" in the title of this tip. You should not only postpone the definition of a variable until you have to use it, but also try to postpone it until you can provide it with an initialization parameter. This avoids the construction and destructor of unnecessary objects, as well as the meaningless invocation of the default constructor. Moreover, in the case of initialization of variables, the purpose of the variable itself is self-evident, so defining the variable here is useful to indicate the meaning of the variable. Remember the practice in the C language? It is best to have a short note next to the definition of each variable to indicate what the variable will do in the future. Now, with a proper name (see Tip 28), combined with meaningful initialization parameters, you can implement every programmer's dream of eliminating unnecessary annotations to it through the reliable variable itself.

Delaying a variable definition can increase the efficiency of the program, enhance the organization of the program, and reduce the annotation of the meaning of the variable.

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.