我的印象是 std::initializer_list
可能表现得像 C++ 中的文字字符串,甚至它们可能会进一步延长 const 引用的生命周期。这是一个正确的评估吗?
initializer_list
中的对象能否在本地范围内以某种方式稍后被引用(不复制它们)?在全局范围内?
例如,此测试在 GCC 和 clang 中通过。 这只是偶然吗?
#include<cassert>
#include<initializer_list>
struct A{
double const* p;
A(std::initializer_list<double> il){ p = &*(il.begin() + 1); };
};
double f(){return 5.;}
int main(){
A a1{1.,2.,3.};
assert( *a1.p == 2. );
A a2{1., f(), f()};
assert( *a2.p == 5. );
}
最佳答案
这是未定义的行为。
在你的例子中,initializer_list
指的是临时数组 const double[3]
,这个数组的生命周期描述如下:
ref The underlying array is not guaranteed to exist after the lifetime of the original initializer list object has ended. [until c++14]
The lifetime of the underlying array is the same as any other temporary object [since c++14]
和
ref All temporary objects are destroyed as the last step in evaluating the full-expression
所以在您的情况下,当调用 A
的构造函数时,将创建具有 3 个 double 值的临时数组,然后您将获取临时数组元素的地址,并且当构造函数结束时,临时数组将被销毁(在此如果完整的表达式是 ctor 的调用),那么 p
就是悬空指针。
关于c++ - 可以延长初始化列表中对象的生命周期吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790972/