General features: Initializer list

code

Syntax

Usage / Usability

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T.

Initializer lists allow the construction of any type using a curly-brace enclosed, comma-separated list of elements {a, b, c}

  • Especially useful for providing easier to use interfaces for container types
  • Critical for the support of a new feature, uniform initialization.

 

PROS

  • Allow use to initialize in-place the items we wish to add in any STL structure (map, vector, etc.)
  • Easy to use with custom classes (need to implement ctor with init list parameter)

CONS

  • Does not allow implicit cast so we need to do it explicitly for that case.

Examples

C++03 code

C++11 code

QUIZ – Will the following code compile?

Answer: YES.

Leave a comment

Your email address will not be published.