Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

questions regarding the design of std::initializer_list

Tags:

c++

c++11

I have some questions regarding the design of std::initializer_list. I didn't find answers in [support.initlist].

Why does it have an explicitly defined default constructor?

Why this constructor is not constexpr?

Why the method size() is not constexpr?

Why there's no traits giving the size of initializer_list (like specializing std::tuple_size)?

Why it's not possible to statically access its elements (like specializing std::get)?

What happens when sizeof is applied to initializer_list?

like image 602
a.lasram Avatar asked Jul 12 '13 20:07

a.lasram


People also ask

How does initializer_ list work?

initializer_list objects are automatically constructed as if an array of elements of type T was allocated, with each of the elements in the list being copy-initialized to its corresponding element in the array, using any necessary non-narrowing implicit conversions.

What is std :: Initializer_list?

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 .


1 Answers

From section 18.9 of the C++ Standard:

An object of type initializer_list provides access to an array of objects of type const E. [ Note: A pair of pointers or a pointer plus a length would be obvious representations for initializer_list. initializer_list is used to implement initializer lists as specified in 8.5.4. Copying an initializer list does not copy the underlying elements. — end note ]

I think the reason for most of these things is that std::initializer_list isn't actually a container. It doesn't have value semantics, it has pointer semantics. Which is made obvious by the last portion of the quote: Copying an initializer list does not copy the underlying elements. Seeing as they were intended solely for the purpose of initializing things, I don't think it's that surprising that you don't get all the niceties of more robust containers such as tuples.

like image 117
Borgleader Avatar answered Oct 04 '22 00:10

Borgleader