简体   繁体   English

std :: initializer列表全局/静态对象的生命周期

[英]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. std::initializer_list主要用作类构造函数/函数参数,以便将列表元素复制到另一个容器中。 But what about creating a global object using std::initializer_list ? 但是使用std::initializer_list创建一个全局对象呢? Eg: 例如:

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 . 如果要查看std::initializer_list模板定义(在Visual Studio 2017中检查),它只包含2个数据成员: const _Elem *_First_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. 在Visual Studio 2017中测试的此类示例看起来效果很好。 But I doubt whether this behaviour corresponds to the latest C++ standard. 但我怀疑这种行为是否符合最新的C ++标准。

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] / 5的类型的对象std::initializer_list<E>是从初始化列表构造为如果所生成的实现和物化(7.4)型“的阵列的prvalue N const E ”,其中N是初始化列表中的元素数。

[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. [dcl.init.list] / 6该数组与任何其他临时对象(15.2)具有相同的生命周期,除了从数组initializer_list对象扩展了数组的生命周期 ,就像绑定对临时对象的引用一样。

Emphasis mine. 强调我的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM