简体   繁体   English

C++ valarray vs 数组大小分配

[英]C++ valarray vs array size allocation

I am allocating a multidimensional valarray of size 2000x2000 and it is working smoothly.我正在分配一个大小为 2000x2000 的多维 valarray,它工作顺利。

valarray<valarray<int>> D(valarray<int>(-2,2000), 2000);
D[1999][1999] = 2000;

However, if I try to allocate a normal array and access an element, I get segmentation fault.但是,如果我尝试分配一个普通数组并访问一个元素,则会出现分段错误。

int A[2000][2000];
A[1999][1999] = 2000;

Both are on the stack, why this difference?两者都在堆栈上,为什么会有这种差异?

Both are on the stack, why this difference?两者都在堆栈上,为什么会有这种差异?

Because std::valarray is much, much smaller object.因为std::valarray比 object 小得多。 Its size is entirely implementation defined, but in a particular standard library implementation that I looked at, it was the size of two pointers.它的大小完全由实现定义,但在我查看的特定标准库实现中,它是两个指针的大小。

By contrast, the size of the 2d array A is more than 15 megabytes assuming a 4 byte int .相比之下,假设 4 字节int ,二维数组A的大小超过 15 兆字节。 The space available for automatic objects (shared among all of them) is typically much less than that in typical language implementations.可用于自动对象(在所有对象之间共享)的可用空间通常远小于典型语言实现中的空间。

Like std::vector , the underlying storage of std::valarray is dynamic, and the size of the object that manages this storage does not depend on the number of elements.std::vector一样, std::valarray的底层存储是动态的,管理此存储的 object 的大小不取决于元素的数量。

This program:这个程序:

#include <iostream>
#include<valarray>

int main() {
    std::cout << "sizeof(std::valarray<std::valarray<int>>): " 
              << sizeof(std::valarray<std::valarray<int>>) << std::endl;
    std::cout << "sizeof(int[2000][2000]): " << sizeof(int[2000][2000]) << std::endl;
}

produces this output for me:为我生产这个 output:

sizeof(std::valarray<std::valarray<int>>): 16
sizeof(int[2000][2000]): 16000000

If you were to use std::array instead, you would have problems, though.但是,如果您要改用std::array ,则会遇到问题。

The dynamic memory allocation is hidden inside of the constructor of the valarray class and still uses new or malloc in the end.动态 memory 分配隐藏在 valarray class 的构造函数中,最后仍然使用 new 或 malloc。

Actually valarray is not on stack.实际上 valarray 不在堆栈上。 This is why construction of array overflow but valarray doesn't.这就是为什么构造数组溢出而 valarray 没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM