C + +: Initialize List

Source: Internet
Author: User

There are two reasons to use the initialization list:

Let's take a look at the first reason--necessity. (1) Initialization of another class member , (2) The member is a constant object, and (3) the member is a reference . Root cause: The compiler always ensures that all member objects are initialized before the constructor body executes (after the initialization of the list) .

The second reason to use the initialization list is for efficiency reasons when the member class has a default constructor and an assignment operator. Suppose you have a class CMyClass with a member of the CString type M_STR, and you want to initialize it to "Hi,how is you." You have two options:

Cmyclass::cmyclass () {cstring::operator= (LPCTSTR); m_str = _t ("Hi,how is You.");

Cstring::cstring (LPCTSTR) Cmyclass::cmyclass (): M_str (_t ("Hi,how is You.")) {}

What's the difference between them? Yes. The compiler always ensures that all member objects are initialized before the constructor body executes, so the code compiled in the first example calls Cstring::cstring to initialize the m_str, which is done before the control arrives at the assignment statement. In the second example, the compiler produces a call to CString:: CString (LPCTSTR) and "Hi,how is you." Passed to this function. The result is that two CString functions (constructors and assignment operators) are called in the first example, and only one function is called in the second example.

Under built-in types such as int or long or other types without constructors, there is no performance difference between the initialization list and the assignment of values in the constructor body. Either way, only one assignment will occur.

C + +: Initialize List

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.