我对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'tstd::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/