Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::initializer_list heap allocate memory?

Simple question, does std::initializer_list heap allocate memory? I'm not talking about its element items, just the buffer itself to store the elements.

like image 881
chewinggum Avatar asked Dec 14 '22 08:12

chewinggum


1 Answers

Here's what cppreference has to say (emphasis mine):

The underlying array is not guaranteed to exist after the lifetime of the original initializer list object has ended. The storage for std::initializer_list is unspecified (i.e. it could be automatic, temporary, or static read-only memory, depending on the situation). (until C++14)

The underlying array is a temporary array of type const T[N], in which each element is copy-initialized (except that narrowing conversions are invalid) from the corresponding element of the original initializer list. The lifetime of the underlying array is the same as any other temporary object, except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary (with the same exceptions, such as for initializing a non-static class member). The underlying array may be allocated in read-only memory. (since C++14)

All that to say, probably not. I can't think of a situation where the compiler or library authors would choose to put it on the heap, but the usage of the word "unspecified" makes it sound like there's no guarantee whatsoever on how the temporary array is allocated. There may be a better specification in the C++ standard.

Another takeaway is you should definitely not try to write the underlying array memory.

like image 111
joshwilsonvu Avatar answered Dec 16 '22 10:12

joshwilsonvu