以下内容可能与平台无关,但无论如何我都会在Win 10 GCC修复它。
假设您在main()的静态内存空间中创建一个数组或向量,其中包含每个可以变量大小的元素:
RADIAL_UNITS = 1000000;
static vector<Pearl> necklace[RADIAL_UNITS] = { };
//each element is a variable-sized vector, which can consist of anywhere from 1-50 Pearl objects
或在main()中的堆栈上分配(假设堆栈空间设置为允许至少1000000个内存地址):
vector<Pearl> necklace[RADIAL_UNITS] = { };
我假设在运行时,necklace
由RADIAL_UNITS
个连续的内存地址组成,指向vector<Pearl>
个元素。我不清楚的是(i)向量元素所在的内存空间(我怀疑堆空间)。
我也感兴趣的附带问题:
我也不清楚(ii)编译器如何知道元素的大小是可变的。 STL容器内部是否有定义的内容可以传达此信息?如果它们是固定大小的,我假设它们在字面上连续存在于我们分配数组的任何区域(第二种情况,即堆栈上的分配,可能会导致段错误,除非放大的默认堆栈空间) 。 (iii)我是否可以修改大小为50*sizeof(Pearl)
的向量元素,以便将它们分配到最初定义为数组的相同内存空间中?珍珠类型由两个烙印点编号组成,因此它们具有固定的尺寸。
答案 0 :(得分:5)
What's not clear to me is in which memory space the
vector
elements reside
Regardless of the space in which the vector
itself is allocated (a fixed-size data structure for tracking elements in its variable-length array) the elements of vector
always reside in dynamic memory, commonly known as "the heap".
It's also not clear to me how the compiler knows that the elements are variable sized. [...] If they were fixed sized, I'm assuming they would literally be contiguously present in whatever region we allocated the array to.
vector
object itself has fixed size. It serves as an "anchor" for a variable-sized array, which is always allocated dynamically. No special treatment is needed from the compiler.
Is it possible for me to fix the vector elements at size
50*sizeof(Pearl)
You cannot do it with vector
, but array
lets you do it:
static array<Pearl,50> necklace[RADIAL_UNITS];