std :: array<>是否会保证仅在堆栈上分配? [英] Does std::array<> guarantee allocation on the stack only?

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

问题描述

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

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<int, 10>.我主要想知道是否允许标准库在其实现内使用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.

推荐答案

我在标准中找不到更明确的答案,但是

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

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

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])带有

  • 没有用户提供的,显式或继承的构造函数([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;是否会保证仅在堆栈上分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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