Does std::arraylt;gt; guarantee allocation on the stack only?(是否 std::arraylt;gt;只保证在堆栈上分配?)
问题描述
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 toNelements 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::arrayis 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<>只保证在堆栈上分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否 std::array<>只保证在堆栈上分配?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
