问题
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.
回答1:
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.
回答2:
That's an interesting question. I agree with Josh's answer, just to want add that I created the following relevant experiment. I tried to compile and run the following code:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = {
#include "x.inc"
};
std::cout << v.size() << std::endl;
}
where x.inc
contained 100M times 0,
plus the trailing 0
, generated by this program:
#include <fstream>
int main()
{
std::ofstream f("x.inc");
for (int i = 0; i < 100000000; i++)
f << "0, ";
f << "0\n";
}
The resulting executable created with GCC had 328 MB, which indicated, that the whole instance of std::intializer_list
was actually presented in the data segment of the program. When run, there was no segmentation fault and Valgrind reported no heap allocation except those 400 MB required by the vector v
.
来源:https://stackoverflow.com/questions/61825532/does-stdinitializer-list-heap-allocate-memory