c++ - 可以延长初始化列表中对象的生命周期吗?

标签 c++ c++11 lifetime initializer-list const-reference

我的印象是 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/

相关文章:

c++ - 使用accessor打印出两种格式的数据

stream - 在多个闭包中表达变量对的生命周期

rust - 如何对 Rust 数组的 2 个可变切片进行操作?

python - 如何使用Python了解进程的生命周期?

c++ - 错误消息与命名右值引用混淆

c++ - 获取二维数组 QPushButton 上 QPushButton 的索引

c++ - 如何摆脱 -Wpointer-arith

c++ - 库设计: allow user to decide between "header-only" and dynamically linked?

c++ - 在cuda中使用静态成员函数模板结构的替代方法?

c++ - 如何声明自引用模板 typedef