In-depth understanding of initialization in C + +

Source: Internet
Author: User

C + + After so many years of development, has become a culture and art, and this art and culture is not inherent in C + +, is the application of C + + in all aspects of the summary and artistic results. C + + looks complicated, but in-depth you'll find that C + + is so beautiful and philosophical. In order to make C + + more artistic, C + + language gurus have paid a lot for this, they are all in the pursuit of simple, the pursuit of the art of programming.
Almost all programming languages have such or such initialization methods, compared with new languages such as C #, many of the initialization techniques are integrated into the compiler, and many programming languages require programmers to implement in a specific way. C + + Initialization technology is largely dependent on programmers. This paper introduces several common and practical initialization techniques.
1. Compile-time initialization
The so-called compile-time initialization, refers to the value of the symbol can be determined at compile time, generally including the initialization of ordinary constants and the use of template technology to construct constants of the initialization technology.
1.1. Constants
such as const int scale = 1;
Enum Colorspace{rgbcolorspace,cmykcolorspace};
Class example{
static const int Count = 1;
}
1.2. Using templates
This is one of the most basic techniques for template meta-programming to be useful. This technique uses the compiler to recursively compile the template to implement a constant initialization. Such as:
template factorial;
template< > Factorial<1>{enum {result=1};};
template< > Factorial{enum {result=n* factorial:: result};};
2. Static initialization
The so-called static initialization refers to the behavior of initializing a global (static) variable or static member programming when the program starts.
2.1. Global variable Initialization
such as int g_globalcount = 1;
static int g_s_globalcount = 1;
2.2. Initialization of static member variables
such as Class example{
Static Example nullexample;
}
Example example::nullexample;
3. Dynamic initialization
This initialization technique takes advantage of the basic characteristics of the class's construction and destructor.
If we need to register a class's creation function to the class factory when the program starts, we can do it in the following way:
Define the macros required for initialization, etc.
typedef geometry* (*CREATEFUNCPTR) ();
struct auto_register{
Auto_register (createfuncptr func) {//register}
~auto_register () {//Cancel registration}
};
#define Auto_register (class_name) \
static const Auto_register _register## class_name # # (Class_name::creategeometry);
Define the implementation based on the above initialization technology
Class geometry{
Public:static geometry* creategeometry () {...}
}
Class diamondgeometry{
Public:static diamondgeometry* creategeometry () {...}
}
Auto_register (Diamondgeometry)
Class rectanglegeometry{
Public:static rectanglegeometry* creategeometry () {...}
}
Auto_register (RectangleGeometry)

A piece of code from the actual project, simplified in the following form:
Switch (t)
{
Case 0:
int a = 0;
Break
Default
Break
}
What's the problem? There seems to be no. Please compile with compiler ...
Well?! An error "Error c2361:initialization of ' A ' is skipped by ' default ' label '. How is that possible?
A few thoughts, realize the interpretation: C + + convention, in a block statement, the scope of the object from the declaration of the object's statement until the end of the block statement, that is, the statement after the default label can use Object A. Jumping from switch to default when the program executes causes object a not to be initialized correctly. Ensuring that objects are initialized is an important design philosophy for C + +, so the compiler will check this violation very strictly, as in the example code above, the default statement does not use a, but given that later code changes may inadvertently be used, so the same is blocked.
Understand the reason, it is easy to solve. Just explicitly restrict the scope of object A to be OK.
Switch (t)
{
Case 0:
{//added for fix problem
int a = 0;
Break
}//added for fix problem
Default
Break
}
If you do need to use object A in the entire switch statement, you can move int a = 0, before moving to the switch statement. However, from the original statement, the intention does not seem to be the case, so recommend the previous solution.

Is it over? No. Let's continue with the exact meaning of "initialization" (that is, initialization) in the error message. C + + is very important to initialize, so often gives us an illusion, it seems that the object in the definition of the process must be initialized. What's the real picture? Just use examples to prove it.
Switch (t)
{
Case 0:
int A;
A = 0;
Break
Default
Break
}
Compile, this time no error. It is obvious that int A; the object is defined but not initialized, otherwise the original error should be reported.
Then look at the user-defined type.
Class B
{
};
Switch (t)
{
Case 0:
b b;
Break
Default
Break
}
There is no error in compiling the result, so classes that do not provide constructors still do not have an initialization process.
If you add a constructor to a class, the situation is different.
Class B
{
Public://added for initialization
B () {}//added for initialization
};
This makes it possible to reproduce the original error. If the constructor is shown, the compiler will initialize and perform a security check on it.

From the above experiments, we can intuitively experience some basic C + + concepts and principles, and improve the depth of cognition.
1.int a = 0; both the declaration and the definition, as well as the initialization; int A; is a declaration or definition depends on the context, but if the definition does not include initialization; a = 0; Just an assignment statement, the object already exists before this sentence.
2. To avoid unnecessary overhead, the compiler does not provide the initialization process by default when the programmer is not explicitly instructed in the code. For certain classes that need to be initialized, provide a constructor. This reveals a C + + philosophy of design: usually you face a variety of options, so please control the code precisely, and its benefits are free to choose the deployment of security, speed, memory overhead and other program features.
3. Pay close attention to the use of the label in the program, especially the case, default and other conventional markings, otherwise they may destroy the correct state of the object. If object initialization is provided, you can get additional help from the compiler.

In-depth understanding of initialization in C + +

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.