Objective C ++ Study Notes-clause 04: Initialize an object before it is used

Source: Internet
Author: User

Make sure that objects are initialized before they're used.

I have read the fourth clause yesterday. The initialization of this article is very rich and I have explained a lot, and some of my questions have been solved. Because I often work overtime and have less time to write, I have to read this article today. So I cannot parse it one by one today, only a few points that I think are important. I also hope you can give me some corrections.

Variable Initialization

C ++ seems capricious about initializing objects. If you write:

Int I;

What will he output? Give you a piece of code

// Initia_four.cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream> using namespace STD; int _ tmain (INT argc, _ tchar * argv []) {int I; cout <I <Endl; system ("pause"); Return 0 ;}

 

As you can see, this is printed. Therefore, you must remember to initialize the variable. When you forget to initialize the variable and then use it again, there will be unexpected disasters.

Constructor Initialization

For objects other than built-in types, the initialization responsibility usually falls on the constructor.The rule is simple:Make sure that each constructor initializes every member of the object. However, it must be clear that the assignment is not initialized. Let's look at the following code. assume there is a type of person. What its constructor does is assign values. Although the person object achieves the expected result, this is not the best practice in C ++.

class Person {public:Person(string n, unsigned int a) {name = n;age = a;}private:string name;unsigned int age;};

The performance of the initialization list is higher than the value assignment operation, because for a string-type name, it must first call the string default constructor, and then assign a new value (copy assignment ), in this way, all the things the default constructor does are wasted. However, for the internal storage type, the performance difference between the assignment and the initialization list is almost no.

Therefore, it is best to initialize the constructor in the following way:

class Person {public:Person(string n, unsigned int a) :name(n),age(a){}private:string name;unsigned int age;};

 

This is very efficient.

Many classes have multiple constructors, each of which has its own initial value column. If this type of classes has many member variables and/or base classes, the existence of multiple Member Initial Value columns will lead to undesirable repetition (within the initial value column) and boring work (for programmers ). In this case, you can reasonably omit the member variables that "assign values as good as initialization" in the initial value column and use their assignment operations instead, and move the value assignment operations to a function (usually private) for all constructors to call. This method is particularly useful when "initial values of member variables are read by files or databases. However, compared to the "pseudo-initialization" (pseudo-initialization) completed by the value assignment operation
Initialization list. Another important point is that: If the member variables are const or refrences, they must have an initial value and cannot be assigned a value.

It must be mentioned that the initial sequence of the initialization list is not initialized according to the order written in the constructor, but the following program compilation is not successful according to the declaration sequence of the member variables.

// Initia_four.cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream> using namespace STD; Template <typename T> class Array {public: array (size_t size): _ SIZE (size) {_ arr = new T [size] ;}~ Array () {Delete [] _ arr;} PRIVATE: size_t _ size; T * _ arr;}; Template <typename T> class safearray {public: safearray (): _ SIZE (5), _ Arr (_ SIZE) {} PRIVATE: array <t> _ arr; size_t _ SIZE ;}; int _ tmain (INT argc, _ tchar * argv []) {safearray <int> Sarr; System ("pause"); Return 0 ;}

Singleton-singleton Mode

Static objects are constructed until the end of the program. Therefore, both stack and heap-based objects are excluded. Such objects include global objects, objects defined in the namespace scope, objects declared as static within the classes, within the function, and within the file scope. Static objects in a function are called local static objects (because they are local for the function), and other static objects are called non-local static objects. Static objects are automatically destroyed when the program ends, that is, their destructor are automatically called at the end of main.

The static variables are defined in different files. Finally, how does the compiler prioritize compilation. If the initialization of a variable is dependent on the variable in another file. To solve this problem, the simplest way is to use Singleton (Singleton mode) to make non-local static a local static

The following code implements the singleton mode:

// Initia_four.cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream> using namespace STD; Class filesystem {}; // Replace the TFS object with the former filesystem & TFS; it may be static in filesystem. {Static filesystem FS; return FS;} class directory {}; Directory: Directory () {STD: size_t disks = TFS (). numdisks ();} directory & tempdir () {static directory TD; return TD;} int _ tmain (INT argc, _ tchar * argv []) {return 0 ;}

But from another perspective, the fact that these functions "contain static objects" gives them uncertainty in a multithreaded system. Once again, any non-const static object, whether it is local or non-local, will be troublesome to "wait for something to happen" in a multi-threaded environment. One way to solve this problem is to manually call all reference-returning functions in the single-thread startup phase of the program, this eliminates the initialization-related "race conditions )".

 

Remember

  • Perform manual initialization for internal objects because C ++ does not guarantee initialization of them.
  • It is best to use the member Initial Value column (member initialization list) in the constructor instead of using the value assignment operation (assignment) in the constructor itself ). The member variables listed in the initial value column should be arranged in the same order as their declaration in class.
  • To avoid the issue of "initialization order across compilation units", replace the non-local static object with the local static object.

 

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.