只保证在堆栈上分配

只保证在堆栈上分配

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

问题描述

std::array(我没有使用 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.

[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.

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

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

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

这个容器是一个聚合类型,与一个结构体具有相同的语义,该结构体包含一个 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;只保证在堆栈上分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:07