gpt4 book ai didi

c++ - std::initializer_list 堆是否分配内存?

转载 作者:行者123 更新时间:2023-12-01 14:03:25 26 4
gpt4 key购买 nike

简单的问题,std::initializer_list 堆是否分配内存?我不是在谈论它的元素项,只是在谈论存储元素的缓冲区本身。

最佳答案

这是 cppreference 必须说的(强调我的):

The underlying array is not guaranteed to exist after the lifetime of the original initializer list object has ended. The storage for std::initializer_list is unspecified (i.e. it could be automatic, temporary, or static read-only memory, depending on the situation). (until C++14)

The underlying array is a temporary array of type const T[N], in which each element is copy-initialized (except that narrowing conversions are invalid) from the corresponding element of the original initializer list. The lifetime of the underlying array is the same as any other temporary object, except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary (with the same exceptions, such as for initializing a non-static class member). The underlying array may be allocated in read-only memory. (since C++14)


尽管如此, 可能不是 。我想不出编译器或库作者会选择将它放在堆上的情况,但是“未指定”一词的使用听起来似乎无法保证临时数组的分配方式。 C++ 标准中可能有更好的规范。
另一个要点是您绝对不应该尝试编写底层数组内存。

关于c++ - std::initializer_list 堆是否分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61825532/

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