A perfect class constructor should be written like this

Source: Internet
Author: User

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 ".

Related Article

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.