Sorry for the awkward title, but I couldn't find a better one.
Consider this sample code (it has no purpose except illustrating the question):
#include <vector>
void FooBar(int);
void func1()
{
static std::vector<int> vec {1, 2, 3, 4};
for (auto & v : vec)
FooBar(v);
}
void func2()
{
for (auto & v : std::vector<int> {1, 2, 3, 4})
FooBar(v);
}
The disassembly of this can be found here
In func1
the static vec
vector is supposed to be constructed once and for all at startup. Actually the disassembly on godbolt mentioned above shows that the initialisation of the static vec
is done only upon the first call of func1
and not at startup, but that's not the point here.
Now consider func2
: here the vector is directly declared "inline" (not sure how this is actually called) inside the for
statement, but of course that vector is constructed every time func2
is called.
Is there a way to declare that vector statically and inside the for
statement, like for (auto & v : static std::vector<int> { 1, 2, 3, 4})
which is unfortunately not legal C++.