1: Efficient initialization.
All member variables are initialized through the initialization list.
If it is initialized in the class constructor, the efficiency will be low!
Because: before entering the class constructor, the class must be a constructed class! That is, its internal member variables have been constructed. That is, before entering the constructor, all the internal member variables have executed the construction with the parameter being null (assuming that the initialization list is not used ).
If you implement the constructor, the compiler will generate the code that calls the constructor. The code here is no longer constructor and is changed to modification!
M_classB = _ B; // here the value assignment operation is executed, not the copy constructor. M_classB has been constructed.
Low Efficiency;
Code Verification:
Class SA
{
Public:
SA (int I): _ I (I ){};
Int _ I;
};
Class F_SA
{
Public:
F_SA (const SA & sa) {m_sa = sa;} // Error
// F_SA (int I = 0): m_sa (I) {} // correct
SA m_sa;
};
Int _ tmain (int argc, TCHAR * argv [])
{
F_SA fsa; // compilation failed !!! M_sa initialization failed through the initialization list! Not called with the appropriate constructor!
System ("pause ");
Return 0;
}
2: prevent resource leakage in constructors.
See Article 10 of Objective C ++. You can use the auto_ptr <> encapsulated pointer to automatically Recycle resources.
3: If the construction fails, an exception should be thrown up.
Suppose there is a member variable pointer that applies for memory through the initialization list. If it fails, it will automatically throw an exception and pass it up. Don't worry about resource leakage in Clause 2
Local exceptions must be handled locally. it is irresponsible to directly throw them to the outside. After local processing, the system filters out the exception and system requirements to external callers, that is, the customer. The next action is called "throwing ".