Constructors should initialize all its member objects through
initializer list if possible. It is more efficient than building the
constructors via assignment inside the constructor body.
Could someone explain, why it is more efficient to use the initializer list with the help of an example?
Consider this program:
On my system (Ubuntu 11.10, g++ 4.6.1), the program produces this output:
Now, consider why it is doing that. In the first case,
C1::C1(int),amust be default-constructed beforeC1‘s constructor can be invoked. Then it is must assigned to viaoperator=. In my trivial example, there is nointassignment operator available, so we have to construct anAout of an int. Thus, the cost of not using an initializer is: one default constructor, oneintconstructor, and one assignment operator.In the second case,
C2::C2(int), only theintconstructor is invoked. Whatever the cost of a defaultAconstructor might be, clearly the cost ofC2:C2(int)is not greater than the cost ofC1::C1(int).Or, consider this alternative. Suppose that we add the following member to
A:Then the output would read:
Now is is impossible to say generally which form is more efficient. In your specific class, is the cost of a default constructor plus the cost of an assignment more expensive than a non-default constructor? If so, then the initialization list is more efficient. Otherwise it isn’t.
Most classes that I’ve ever written would be more efficiently initialized in an init list. But, that is a rule-of-thumb, and may not be true for every possible case.