对象的内存分配 [英] memory allocation for objects

查看:61
本文介绍了对象的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在函数中实例化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.

所以,我的问题是:

  1. 不同类(由c ++提供或用户定义的类)的对象呢?他们的对象在哪里实例化?例如:假设Employee是一个类,我们声明Employee emp;.堆栈或堆中的emp在哪里给出了space->?

  1. 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 is emp 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?

推荐答案

  1. 这取决于.如果Employee具有仅在堆栈上分配的成员,则整个对象为.但是,Employee可能具有指针成员,并且Employee的构造函数可能会在堆上为其分配内存.然后一些成员在堆上,一些在堆栈上.

  1. It depends. If Employee has members, that are allocated only on the stack, then the whole object is. BUT, Employee may have pointer members and Employee's constructor may allocate memory for them on the heap. Then some of the members are on the heap, some on the stack.

是.

这篇关于对象的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆