C++ Constructor後面的":"是什麼鬼意思? (Initialization List 教學)
Initializer List
Initializer List用於初始化Class的Data member。 Constructor(構造函數)將要初始化的member list放在冒號後面(以逗號分隔)。
1 |
|
什麼時侯要用 Initializer List?
在某些情況下,我們無法直接初始化Constructor(構造函數)中的Data member,而必須使用“Initializer List(初始化列表)”。
當你要初始化 non-static const data member
const Data member 必須使用Initializer List進行初始化。
例子:
1 |
|
t
是Test類的const data member,並使用Initializer List進行初始化。
Reason for initializing the const data member in initializer list is because no memory is allocated separately for const data member, it is folded in the symbol table due to which we need to initialize it in the initializer list.
另外,它是一個copy constructor(複制構造函數),我們不需要調用賦值運算符(±*/那些),這意味著我們避免了一個額外的操作。
當你要初始化 reference member
當你要初始化帶有&的Data member,你都要用到Initializer List。
1 | // Initialization of reference data members |
當你要初始化沒有constructor的 member object
在以下示例中,Class A
的 Object a
是 Class B
的 data member,而 A
沒有默認的Constructor。
這時侯必須用Initializer List來初始化 a
。
1 |
|
假設現在Class A
同時具有默認Constructor和參數化Constructor。
如果要使用默認Construct初始化a
,則不必使用Initializer List,而必須使用參數化(Parameterized)Constructor初始化a
。
當你要初始化 base class members
Base class 的 Parameterized Constructor 只能使用nitializer List進行呼叫。
1 |
|
當Constructor的參數名稱與Data member相同時
如果Constructor的參數名稱與Data member名稱相同,則必須使用此Pointer(指針)或Initializer List來初始化Data member。 在以下示例中,A()
的member名稱和parameter名稱均為i
。
1 |
|
從Performance角度
最好在Initializer List中初始化所有Class variable,而不是在body內部assign value。
看看以下示例:
1 | // Without Initializer List |
Here compiler follows following steps to create an object of type MyClass
- Type’s constructor is called first for
a
. - The assignment operator of
Type
is called inside body ofMyClass()
constructor to assign
1 | variable = a; |
- And then finally destructor of
Type
is called fora
since it goes out of scope.
Now consider the same code with MyClass()
constructor with Initializer List
1 | // With Initializer List |
With the Initializer List, the following steps are followed by compiler:
- Copy constructor of
Type
class is called to initialize:variable(a)
. The arguments in the initializer list are used to copy constructvariable
directly. - The destructor of
Type
is called fora
since it goes out of scope.
As we can see from this example if we use assignment inside constructor body there are three function calls: constructor + destructor + one addition assignment operator call. And if we use Initializer List there are only two function calls: copy constructor + destructor call. See this post for a running example on this point.
Reference
What does the colon after a constructor mean?
Variables after the colon in a constructor
Understanding Initialization Lists in C++
建構函式 (C++)
When do we use Initializer List in C++?