是否 std::array<>只保证在堆栈上分配?

Does std::arraylt;gt; guarantee allocation on the stack only?(是否 std::arraylt;gt;只保证在堆栈上分配?)
本文介绍了是否 std::array<>只保证在堆栈上分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::array<int,10>(我自己不使用 new)是否保证被 C++ 标准分配在堆栈中而不是堆中?

Is std::array<int,10> (without myself using new) guaranteed to be allocated in the stack rather then the heap by the C++-Standard?

要清楚,我的意思不是 new std::array.我主要想知道,是否允许标准库在其实现中使用 new.

To be clear, I do not mean new std::array<int, 10>. I mainly wonder, if the standard library is allowed to use new inside its implementation.

推荐答案

我在标准中找不到更明确的答案,但是 [array.overview]/2:

I could not find more explicit answer in the standard, but [array.overview]/2:

数组是一个聚合 ([dcl.init.aggr]),最多可以用 N 个元素进行列表初始化类型可转换为 T.

An array is an aggregate ([dcl.init.aggr]) that can be list-initialized with up to N elements whose types are convertible to T.

还有 [dcl.init.aggr]/1:

聚合是一个数组或一个类(子句[class])with

  • 没有用户提供的、显式或继承的构造函数([class.ctor]),
  • no user-provided, explicit, or inherited constructors ([class.ctor]),

...

这差不多涵盖了它.聚合不可能动态分配内存(或者可能在构建过程中自己做任何事情).只有一个隐式声明的普通构造函数.

That about covers it. No way an aggregate could allocate memory dynamically (or perhaps, do anything at all at its own during the construction). There's only an implicitly-declared trivial constructor.

当然,如果你new std::array<...>,你会在堆"上得到一个数组.

Of course, if you new std::array<...>, you get an array on "the heap".

有些人可能对我们在 cppreference 上获得的内容更满意:

Some may be more satisfied by what we can get on cppreference:

std::array是封装固定大小数组的容器.

std::array is a container that encapsulates fixed size arrays.

此容器是一种聚合类型,其语义与将 C 样式数组 T[N] 作为其唯一非静态数据成员的结构相同.

This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member.

<小时>

第三,std::array是在C++11中引入的.为什么?例如,在某些方面补充 std::vector,例如在不允许动态分配的 constexpr 函数中使用.


Thirdly, std::array was introduced in C++11. Why? For example, to complement std::vector in some ways, like usage in constexpr functions, where dynamic allocation is not allowed.

这篇关于是否 std::array&lt;&gt;只保证在堆栈上分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)