Uniform Initialization ( List Initialization ): C++ 11

Uniform Initialization ( List Initialization ): C++ 11

Topics Covered :

Uniform Intializer list

       Direct list initialization

      Copy-list-initialization

About std::initilizer_list

Problem associated with std::initializer_list

std::initializer_list for Aggregate types [Special case with empty braces]

Uniform initialization is also called list initialization. It is broadly categories into two categories

  • Direct-list-initialization :
    Example:

Foo foo{1,2};  //here {} is called braced init list, it is not std::initializer_list, but it implicitly converts to std::initializer_list.

 

  • 2. Copy-list-initialization :

Example:

Foo foo = {1,2};

 

About std::initializer_list :

In a C++ initialization list, which is a list of elements with the type const T, this type is used to access the values.

The compiler automatically creates objects of this type from initialization list declarations, which are lists of components separated by commas and wrapped in braces.

Problem Associated with std::initializer_list:

Problem 1: initializer_list cannot be use in template

template<typename T, size_t N>
auto test()
{
   return vector<T>{N};
}


int main()
{
   return test<string, 3>().size();   //return vector with 3 string and size return 3.
}

Now, when the same return statement is replaced with,
test().size(); test returns 1 and hence it will be problematic.

 
Problem 2: Initializer_list doesn’t work with move-only types.

std::vector<int> v1(10, 0);  // vector with 10 elements intialized with 0
std::vector<int> v2 {3, 0};  // vector contain 3, 0

std::string s1(5,'a'); //'aaaaa'
std::string s2{48, 'a'}; //0a

 
problem 3: Initializer_list doesn’t work macros at all.

 

std::initializer_list for Agregate types [Special case with empty braces]:

template<typename T>
struct Foo {
    Foo() {};
	Foo(std::initializer_list<int> a){});
	int i;
}

int main()
{
  Foo<int> foo{};  

      // 1. calls default constructor.
      //2. if the default constructoris not present then calls constructor with initializer_list.
      //3. If constructor is default then zero value initializationis invoked.

     //Foo() = default , i will get initialized with zero.
}