The std::initializer_list
is mostly used as class constructors/functions argument in order to copy the list elements into another container. But what about creating a global object using std::initializer_list
? E.g.:
struct ElemType {
const char* name;
bool flag;
};
std::initializer_list<ElemType> MyGlobalData = { {"One",true}, {"Two",false} };
If to look at the std::initializer_list
template definition (checked in Visual Studio 2017), it contains only 2 data members: const _Elem *_First
and _Last
.
It means that the initializer list data should be stored in an automatic variable. What is its lifetime in this case?
Such example tested in Visual Studio 2017 looks working good. But I doubt whether this behaviour corresponds to the latest C++ standard.
It's well defined.
[dcl.init.list]/5 An object of type
std::initializer_list<E>
is constructed from an initializer list as if the implementation generated and materialized (7.4) a prvalue of type "array ofN
const E
", whereN
is the number of elements in the initializer list.[dcl.init.list]/6 The array has the same lifetime as any other temporary object (15.2), except that initializing an
initializer_list
object from the array extends the lifetime of the array exactly like binding a reference to a temporary.
Emphasis mine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With