简体   繁体   English

C ++中的堆栈和堆内存

[英]Stack and heap memory in c++

If I declare a variable as如果我将变量声明为

 int a[100]

it is said that an array with 100 elements created on stack, and can be a bad idea depending on size etc.据说在堆栈上创建了一个包含 100 个元素的数组,并且根据大小等可能是一个坏主意。

Consider I define a structure考虑我定义了一个结构

 struct abc
 {
    int a[100];
 };

and somewhere in code I utilize this structure as在代码中的某处,我将这种结构用作

 abc P; //line 1
 abc *p = new abc(); //line 2

Now the array is inside these two objects( one on stack(line 1) and one on heap (line 2) ).现在数组位于这两个对象内(一个在堆栈上(第 1 行),一个在堆上(第 2 行))。 Where does the internal array reside?内部阵列在哪里?

Thanks谢谢

The location for a data member depends on the location of the object contains it.数据成员的位置取决于包含它的对象的位置。 When the struct is on the stack, all its members are on the stack.当结构在堆栈上时,它的所有成员都在堆栈上。 When the struct is on the heap, so are the members.当结构在堆上时,成员也在堆上。

In line 1 the array is on the stack.在第 1 行,数组在堆栈上。

In line 2 the array is on the heap.在第 2 行中,数组位于堆上。

The struct is seen as one big variable containing all the internal arrays (and perhaps some more memory for padding and aligning) and the entire thing resides where you out it - stack or heap.该结构体被视为一个包含所有内部数组的大变量(可能还有一些用于填充和对齐的内存),并且整个事物都驻留在您所在的位置 - 堆栈或堆。

This is why you can assign struct to struct, like这就是为什么您可以将结构分配给结构,例如

s1 = s2;

and all the arrays get copied - it is handled as one big chunk of data (although it's a shallow copy, the arrays occupy real memory).并且所有数组都被复制 - 它被作为一大块数据处理(虽然它是一个浅拷贝,但数组占用了实际内存)。

它与对象在同一位置,因为当对象在堆上并且内部数组在堆栈上时,数组将被删除,最终得到一个空对象。

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

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