在标准(C ++ 17)中,它表示支持const std::string
的{{1}}数组:
该数组具有与任何其他临时对象相同的生存期,只不过从该数组初始化一个initializer-list对象可以延长该数组的生存期,就像将引用绑定到一个临时对象一样。
在您的代码中,动态分配的initializer-list对象由数组初始化,因此该文本适用。
将引用绑定到新初始化器内部的临时的生命周期延长规则是:(C ++ 17 [class.temporary] /6.3)
在 new-initializer 中引用的临时绑定一直存在,直到包含 new-initializer 的完整表达式完成为止。 [示例:
initializer_list
因此,似乎在包含struct S { int mi; const std::pair<int,int>& mp; };
S a { 1,{2,3} };
S* p = new S{ 1,3} }; // Creates dangling reference
的行的末尾破坏了后备数组,因此在此之后尝试对其进行检查将导致未定义的行为(这意味着您可能会或可能不会看到期望的结果)。 / p>
,
所以我写了一个完整的例子:
#include <iostream>
#include <string>
void print(std::initializer_list<std::string> &il)
{
for (auto &s: il) std::cout << s << ' ';
std::cout << std::endl;
}
int main( void ) {
auto a = std::initializer_list<std::string>{"1","2","3","4"};
auto b = new std::initializer_list<std::string>{"5","6","7","8"};
print (a);
print (*b);
}
编译器告诉我出了什么问题:
$ clang++ std=c++17 so.cpp
so.cpp:12:49: warning: array backing the allocated initializer list will be destroyed at the end of the full-expression
[-Wdangling-initializer-list]
auto b = new std::initializer_list<std::string>{"5","8"};
^~~~~~~~~~~~~~~~~~~~
1 warning generated.
本文链接:https://www.f2er.com/2539998.html