c++ - std::array 的堆栈分配和堆栈溢出错误

标签 c++ arrays

我对std::array的分配做了少量研究和 std::vector

我目前的(简单的)理解是:

std::vector是一个对象,它包含指向其值的数组/集合/缓冲区的指针

std::array是一个保存其数组/集合/缓冲区的对象

一个非常不正确但有效的证明是

printf("%llu\n", sizeof(*new std::vector<uint64_t>(10)));
printf("%llu\n", sizeof(*new std::array<uint64_t, 10>));

24 (consisting of vector things)
80 (consisting of uint64_t[10])

定义一个变量在栈上定义它

定义 std::array在堆栈上定义/分配它的数组/集合/缓冲区 - 那么为什么不 std::array<uint64_t, 1000000000000000> array (1 PB) 导致堆栈溢出?

为什么在栈上定义一个超过栈大小的对象不会导致段错误?

最佳答案

printf("%llu\n", sizeof(*new std::vector<uint64_t>(10)));
printf("%llu\n", sizeof(*new std::array<uint64_t, 10>));

首先,都不是 std::vector<uint64_t> 的对象也不std::array<uint64_t, 10>在这里创建是因为该表达式出现在 Unevaluated Contexet 中.

Defining an std::array defines/allocates it's array/collection/buffer on the stack - so why doesn't std::array<uint64_t, 1000000000000000> array (1 PB) cause a stack overflow?

您可能仍在未评估的上下文中这样做。 Demo .

但是,在评估的上下文中,例如:

int main(){
    std::array<uint64_t, 1000000000000000> arr;
}

现在,根据您的环境,您可能会遇到段错误。您还应该知道,编译器可能会优化代码(因为无法访问元素)。

其次,您的代码片段不是估算包含元素的容器消耗的内存的方法。对于 std::array我们可能会做出假设并接受您的代码的变体,但肯定不会 std::vector .

关于c++ - std::array 的堆栈分配和堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001055/

相关文章:

c++ - 程序无法启动,因为您的计算机缺少 libgcc_s_dw2-1.dll。简单控制台

java - 在java中将多个结果保存在数组中

c++ - Socket getaddrinfo() - VxWorks 的等效函数?

c++ - 如何在方法中获取 int 数组(方法参数)的长度?

android - 如何将字节数组中的图像文件数据转换为位图?

php - 检查字符串是否以特定单词开头,如果是则拆分

c++ - 我需要帮助结束更新二维数组的循环

python - Numpy 始终将邻居获取为 3x3 矩阵

C++ 模板 : calculate values and make decisions at compile time

c++ - 将 char* 转换为 int* 的结果是什么