是否 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 toN
elements whose types are convertible toT
.
还有 [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.
相关文章