对象的内存分配 [英] memory allocation for objects
问题描述
当我们在函数中实例化c ++中的变量,例如int x
(即x是局部变量)时,它被分配在进程堆栈的顶部.但是,如果执行int *x= new int
,则会在堆中提供空间.
When we instantiate a variable in c++ like int x
within a function(i.e. x is a local variable), it is allocated on top of stack of the process. But if we do int *x= new int
, the space is provided in heap.
所以,我的问题是:
-
不同类(由c ++提供或用户定义的类)的对象呢?他们的对象在哪里实例化?例如:假设Employee是一个类,我们声明
Employee emp;
.堆栈或堆中的emp
在哪里给出了space->?
What about objects of different classes (classes provided by c++ or user defined)? Where are their objects instantiated? For example: Let Employee is a class and we declare
Employee emp;
. Where isemp
given space-> on stack or in heap?
如果声明int a[4]
在函数内,那么a
的所有四个单元格是否都获得堆栈空间?
If the declaration int a[4]
is within a function, do all the four cells of a
get space on stack?
推荐答案
-
这取决于.如果
Employee
具有仅在堆栈上分配的成员,则整个对象为.但是,Employee
可能具有指针成员,并且Employee
的构造函数可能会在堆上为其分配内存.然后一些成员在堆上,一些在堆栈上.
It depends. If
Employee
has members, that are allocated only on the stack, then the whole object is. BUT,Employee
may have pointer members andEmployee
's constructor may allocate memory for them on the heap. Then some of the members are on the heap, some on the stack.
是.
这篇关于对象的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!