GoldenSpecOps GoldenSpecOps - 7 days ago 6
C++ Question

Benefits of std::initializer_list in c++11

I wondered what are the benefits of using

std::initializer_list
, and what purpose does it serve.

I encountered the following: Why is list initialization (using curly braces) better than the alternatives?

and understood that the "non-narrowing" effect, although I can't really see how beneficial it is.

Another benefit I can spot, is the relative ease of use when initializing ( for example when initializing a class with several members ), but besides that I don't see any major improvement, which really makes initialization using initializer_list a good practice, especially in terms of efficiency.

Answer

For most practical purposes, std::initializer_list gives one benefit: the ability to initialize objects of arbitrary type.

Lack of narrowing is nice, but absolutely pales by comparison to simple convenience of being able to type something like:

std::vector<int> foo { 1, 2, 3, 4};

rather than:

std::vector<int> foo;
foo.push_back(1);
foo.push_back(2);
foo.push_back(3);
foo.push_back(4);

...or the multitude of hacks that spawned, mostly based around abusing overloading of the comma operator to get syntax like:

std::vector<int> foo;
foo += (1, 2, 3, 4);

Yes, this can have some tangible benefits in terms of speed (for one example) since the vector will pre-allocate space to prevent reallocation during the initialization from the initializer_list. This is clearly a good thing--but being at all honest, it's rarely a deal-maker. If the intializer_list were more convenient but likely to be slower by some small percentage, people would use it anyway (and quite rightly so, in most cases).

Comments