1

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.

Community
  • 1
  • 1
Eliran Abdoo
  • 611
  • 6
  • 17
  • 1
    So your question is actually *Why is the "non-narrowing" effect of std::initializer_list beneficial*? – Christian Hackl Nov 26 '16 at 12:22
  • Indeed, and any other benefit which perhaps I don't know of, is most welcome. – Eliran Abdoo Nov 26 '16 at 12:25
  • 1
    I think that would be two different questions. The first would probably be sufficiently specific. The second one, however, would be strange and may closed as a duplicate. After all, that other question has a lot of answers with *many, many* benefits explained, so what more would you expect? – Christian Hackl Nov 26 '16 at 12:29
  • 2
    I don't think performance was a major reason, but ease of use and avoiding common bugs like narrowing conversions and [the most vexing parse](http://stackoverflow.com/questions/1424510/most-vexing-parse-why-doesnt-a-a-work). – Bo Persson Nov 26 '16 at 12:35
  • In case the initializer_list provides a vast range of benefits, then this question really should be closed and I should hit the books, and an explanation for the benefits of the non-narrowing effect will be suffice in that case. – Eliran Abdoo Nov 26 '16 at 12:37

1 Answers1

2

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).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111