Why isn't std::initializer_list a language built-in?

前端 未结 6 2189
再見小時候
再見小時候 2020-12-12 15:39

Why isn\'t std::initializer_list a core-language built-in?

It seems to me that it\'s quite an important feature of C++11 and yet it doesn\'t have its

6条回答
  •  独厮守ぢ
    2020-12-12 16:31

    The C++ Standard Committee seems to prefer not to add new keywords, probably because that increases the risk of breaking existing code (legacy code could use that keyword as the name of a variable, a class, or whatever else).

    Moreover, it seems to me that defining std::initializer_list as a templated container is quite an elegant choice: if it was a keyword, how would you access its underlying type? How would you iterate through it? You would need a bunch of new operators as well, and that would just force you to remember more names and more keywords to do the same things you can do with standard containers.

    Treating an std::initializer_list as any other container gives you the opportunity of writing generic code that works with any of those things.

    UPDATE:

    Then why introduce a new type, instead of using some combination of existing? (from the comments)

    To begin with, all others containers have methods for adding, removing, and emplacing elements, which are not desirable for a compiler-generated collection. The only exception is std::array<>, which wraps a fixed-size C-style array and would therefore remain the only reasonable candidate.

    However, as Nicol Bolas correctly points out in the comments, another, fundamental difference between std::initializer_list and all other standard containers (including std::array<>) is that the latter ones have value semantics, while std::initializer_list has reference semantics. Copying an std::initializer_list, for instance, won't cause a copy of the elements it contains.

    Moreover (once again, courtesy of Nicol Bolas), having a special container for brace-initialization lists allows overloading on the way the user is performing initialization.

提交回复
热议问题