Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of a std::initializer list global/static object

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.

like image 427
RedSoft Avatar asked Dec 26 '18 15:12

RedSoft


1 Answers

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 of N const E", where N 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.

like image 111
Igor Tandetnik Avatar answered Oct 22 '22 23:10

Igor Tandetnik