c++中的结构内存分配
Structure memory allocation in c++
众所周知,结构的内存是在定义变量时(或创建实例时)分配的。
现在
struct Programmer {
int skills;
int problemSolved;
};
int main(){
Programmer me;//Here the memory will be allocated but in what
//format(discrete or continuous block of memory)?
me.skills = 10;
me.problemSolved = 2000;
return 0;
}
分配给结构实例或变量的内存是连续块(如数组)还是离散块内存?如果是那么为什么?
该结构在堆栈上分配,在一个连续的内存块中(在这种情况下可能是 64 位)。它是在调用函数时分配的(除非你的编译器做了一些棘手的事情)。
所有实例变量都在堆栈上分配(虽然标准中没有指定它们是如何分配的,但所有编译器都是这样做的)。原因是,当你递归地调用一个函数时,它会为更多的变量获得一个新的栈帧。这样,如果您在堆栈上有一个变量 "me",并且您从 main() 中调用 main(),您最终会在第二个堆栈帧中得到第二个 "me" 变量。当第二个 "main()" returns 时,堆栈帧被释放以供将来其他调用使用。
分配给 struct
的内存是连续的。来自 C11 标准草案的§6.2.5 ¶20:
A structure type describes a sequentially allocated nonempty set of
member objects....
但是,根据 §6.7.2.1 ¶15:
,分配给 struct
的存储空间内可能存在填充
There may be unnamed padding within a structure object, but not at its
beginning.
并且,来自 6.7.2.1 ¶17:
There may be unnamed padding at the end of a structure or union.
众所周知,结构的内存是在定义变量时(或创建实例时)分配的。
现在
struct Programmer {
int skills;
int problemSolved;
};
int main(){
Programmer me;//Here the memory will be allocated but in what
//format(discrete or continuous block of memory)?
me.skills = 10;
me.problemSolved = 2000;
return 0;
}
分配给结构实例或变量的内存是连续块(如数组)还是离散块内存?如果是那么为什么?
该结构在堆栈上分配,在一个连续的内存块中(在这种情况下可能是 64 位)。它是在调用函数时分配的(除非你的编译器做了一些棘手的事情)。
所有实例变量都在堆栈上分配(虽然标准中没有指定它们是如何分配的,但所有编译器都是这样做的)。原因是,当你递归地调用一个函数时,它会为更多的变量获得一个新的栈帧。这样,如果您在堆栈上有一个变量 "me",并且您从 main() 中调用 main(),您最终会在第二个堆栈帧中得到第二个 "me" 变量。当第二个 "main()" returns 时,堆栈帧被释放以供将来其他调用使用。
分配给 struct
的内存是连续的。来自 C11 标准草案的§6.2.5 ¶20:
A structure type describes a sequentially allocated nonempty set of member objects....
但是,根据 §6.7.2.1 ¶15:
,分配给struct
的存储空间内可能存在填充
There may be unnamed padding within a structure object, but not at its beginning.
并且,来自 6.7.2.1 ¶17:
There may be unnamed padding at the end of a structure or union.