1. A constant exists in a class member, such as const int A. It can only be initialized and cannot be copied.
2. A reference exists in the class members. You can only use initialization and cannot assign values.
3. Improve Efficiency
To improve efficiency, try to use initialization in clause 12 of Objective C ++ instead of assigning values in constructors:
Template <class T> class namedptr {public: namedptr (const string & initname, T * initptr );... PRIVATE: const string & name; // You must initialize T * const PTR through the member initialization list // You must initialize through the member initialization list };
The previous class template does not contain const and reference members. Even so, it is better to initialize the list with members than to assign values in the constructor. The reason for this is efficiency. When the list is initialized using members, only one string member function is called. In the constructor, two values are called. To understand why, see what happened when declaring the namedptr <t> object.
The object can be created in two steps:
1. Data member initialization.
2. Execute the actions in the called constructor body.
(For objects with a base class, the initialization of the base class members and the execution of the constructor bodies take place before the member initialization of the derived class and the execution of the constructor bodies)
For the namedptr class, this means that the string object name constructor is always called before the program runs to the namedptr constructor. The question is: which constructor of string will be called?
This depends on the list of namedptr class member initialization. If no initialization parameter is specified for name, the default string constructor is called. When a value is assigned to the name in the namedptr constructor, operator = function is called for the name. So there are two calls to the string member function in total: one is the default constructor, and the other is the value assignment. On the contrary, if you use a member initialization list to specify that the name must be initialized using initname, the name will be initialized by copying the constructor at the cost of one function call. Even for a simple string type, unnecessary function calls can cause a high price. As classes become larger and more complex, their constructors become more and more complex, and the cost of object creation increases. The habit of using the member initialization list as much as possible can not only meet the const and reference member initialization requirements, but also greatly reduce the chance of inefficient data member initialization.
Benefits of using the initialization list