I'm running on Debian unstable with GCC 9.3.0.
There was a recent change on a project I work on that introduced code similar to what's below.
#include <initializer_list>
#include <map>
#include <vector>
std::map<int, std::vector<int>> ex = []{
/* for reused lists */
std::initializer_list<int> module_options;
return (decltype(ex)) {
{1, module_options = {
1, 2, 3
}},
{2, module_options},
};
}();
The idea is that identical subsections of the initializer lists are first declared at the top, defined and assigned to the std:initializer_list
variable at the first usage, then used in multiple places. This is convenient, and some may argue more readable, which is why it was accepted.
All was well until a few days ago where GCC started throwing a init-list-lifetime
warning on the code. We use -Werror
in our regression, so this fails the regression for me. I also tried compiling with clang 9.0.1, which does not throw the warning.
<source>: In lambda function:
<source>:12:9: warning: assignment from temporary 'initializer_list' does not extend the lifetime of the underlying array [-Winit-list-lifetime]
12 | }},
| ^
According to cppreference:
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).
So my understanding is that the common initializer list value, being defined within the scope of an encompassing initializer list, has a lifetime that ends with the enclosing initializer list. From the cppreference page earlier, it mentions that std::initializer_list
is a "lightweight proxy-object", which implies that it does not take ownership of the temporary object or extend it's lifetime. This means that the underlying array is not guaranteed to exist in later usage, which is why the warning is being thrown. Is this analysis correct?
I can prevent the warning from occuring by moving the std::initializer_list
variable initialization to the declaration. For full details on the problem as it stands in the project see the PR.
std::initializer_list
is just not designed to stick around. Using anstd::vector
instead would avoid these concerns. Your MCVE makes it seem like the initialization data is constant. In that case, you can use aconstexpr
array which will help the compiler generate the best code it can. – François Andrieux Jul 13 '20 at 14:54std::vector
or aconstexpr int[]
to hold the values? That's similar to what the linked PR does. – ktb Jul 13 '20 at 15:17