[Cs3] initializer lists

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Feb 11 17:30:53 EST 2014


> In terms of initializer lists, I had no idea you could initialize
> member variables that way. I only knew that you could use them to
> call base-class non-default constructors. Now that I know, I'm
> wondering: Is there any difference performance-wise between for
> example:
>
> Test::Test(int a, int b) : a_ = a, b_ = b{}
>
> and
> 
> Test::Test(int a, int b)
> {
>   a_ = a;
>   b_ = b;
> }
> 
> or is the difference purely stylistic?

First, it should be

       Test::Test(int a, int b) : a_ (a), b_ (b){}

For primitive (basic) types, there is no semantic difference. Yet,
initializer list gives a compiler more information as to how to
optimize member variable initialization (so it is preferred for this
reason).

However, if Test is a derived class, then member initialization list
may contain the invocation of a constructor for the base
class. Moreover, this constructor does not have to be a default
(no-argument) constructor. Same goes for the member variables that are
objects. A common idiom is to pass some of the derived constructor
parameters to the base classes.

Furthermore, initializers may be used to initialize constant fields
(which otherwise cannot be updated).

Since there is no disadvantage to using initializer lists, a good
practice  is to use them when you can.

Thanks,
-- 
Mikhail


More information about the cs3 mailing list