Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of using initializer list? [duplicate]

Tags:

c++

Possible Duplicate:
Benefits of Initialization lists

I was wondering if there was an advantage to initializing members with the initializer list over putting these in the constructor. Certain things have to use the initialize list but for the majority of things that don't, is there a difference? I prefer the latter because when I have multiple constructors, I prefer simply calling construct() to promote code reuse.

Thanks

like image 660
jmasterx Avatar asked Nov 27 '10 02:11

jmasterx


2 Answers

If you don't use the initializer list, the member or base class gets default constructed before the opening curly brace.

So, your calls to set it later will add an operator=() call.

If you use the initializer list, the member or base class has the proper constructor called.

Depending on your classes, this might be required or faster.

like image 152
Lou Franco Avatar answered Sep 30 '22 07:09

Lou Franco


For primitives, there is no difference between using initializer lists or constructing them via assignment.

For other types, initializer lists might afford you performance improvements when constructing objects.

Do note that the order of initializing (in initializer lists) depends on the order of declaration in the class. If the declarations are out of order and you need to construct data that depends on something else already being initialized before hand, that is an exception to the 'use initialization lists when possible rule'.

More info: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

like image 40
逆さま Avatar answered Sep 30 '22 06:09

逆さま