std :: initializer_list堆是否分配内存? [英] Does std::initializer_list heap allocate memory?

查看:75
本文介绍了std :: initializer_list堆是否分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,std :: initializer_list堆是否分配内存?我不是在谈论其元素项,而只是在谈论用于存储元素的缓冲区本身.

Simple question, does std::initializer_list heap allocate memory? I'm not talking about its element items, just the buffer itself to store the elements.

推荐答案

以下是 cppreference的内容不得不说(强调我的意思):

Here's what cppreference has to say (emphasis mine):

在原始初始化程序列表对象的生命周期结束后,不能保证基础数组存在.std :: initializer_list的存储为未指定(即根据情况可能是自动,临时或静态只读存储器).(直到C ++ 14)

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)

基础数组是类型为const T [N]的临时数组,其中每个元素都从原始初始值设定项列表的相应元素进行复制初始化(除非缩小转换无效).基础数组的生存期与任何其他临时对象相同,不同之处在于,从数组初始化initializer_list对象可以延长数组的生存期,就像将引用绑定到临时对象一样(但有相同的例外,例如用于初始化非临时对象).-static类成员).底层数组可以分配在只读存储器中.(自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)

所有这些,可能不是.我想不出编译器或库作者会选择将其放到堆上的情况,但是"unspecified"一词的用法很特殊.听起来好像无法保证临时数组的分配方式.C ++标准中可能有更好的规范.

All that to say, probably not. I can't think of a situation where the compiler or library authors would choose to put it on the heap, but the usage of the word "unspecified" makes it sound like there's no guarantee whatsoever on how the temporary array is allocated. There may be a better specification in the C++ standard.

另一个要点是,您绝对不应该尝试写入基础数组内存.

Another takeaway is you should definitely not try to write the underlying array memory.

这篇关于std :: initializer_list堆是否分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆