gpt4 book ai didi

c++ - initializer_list 和 GCC 4.9.2 与 GCC trunk

转载 作者:可可西里 更新时间:2023-11-01 16:39:47 30 4
gpt4 key购买 nike

以下是问题的精简版:

#include <initializer_list>
#include <iostream>

enum objects { zero, one, two, three, four, five, six, seven };

std::initializer_list<objects> objects_list()
{
return { zero, one, two, three, four, five, six, seven };
}

int main()
{
for (auto a : objects_list())
{
std::cout << a << ' ';
}
std::cout << '\n';
}

我的期望是程序输出:

0 1 2 3 4 5 6 7

这是由 GCC 4.9.2 确认的,但是来自其 git 存储库的 GCC 会产生:

0 0 -85997960 32712 -1076836160 32765 0 32

这看起来基本上是随机数。

我的程序或 GCC 有问题吗?

最佳答案

N4296 § 8.5.4/5 州

An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated a temporary array of N elements of type const E, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list<E> object is constructed to refer to that array

所以我们被告知 std::initializer_list引用一个临时数组。

和 § 8.5.4/6 状态

The array has the same lifetime as any other temporary object

标准提供了这个例子来证明在数组超出范围后访问初始化列表是未定义的行为:

struct A {
std::initializer_list<int> i4;
A() : i4{ 1, 2, 3 } {} // creates an A with a dangling reference
};

the initializer_list object is initialized in a constructor’s ctor-initializer, so the array persists only until the constructor exits, and so any use of the elements of i4 after the constructor exits produces undefined behavior. —end example ]

您有一个类似但略有不同的示例,该示例涉及复制:

std::initializer_list<objects> objects_list()
{
return { zero, one, two, three, four, five, six, seven };
}

根据标准逻辑,数组 {zero, one, two, ...}仅在 objects_list 期间持续存在功能。

18.9/2 [support.initlist] 也支持拷贝不会持久化底层数组:

Copying an [std::]initializer list does not copy the underlying elements.

所以我相信您的代码最终是 UB,而且它之前能正常工作这一事实纯属运气。

关于c++ - initializer_list 和 GCC 4.9.2 与 GCC trunk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762154/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com