memory allocation for objects

空扰寡人 提交于 2020-01-02 04:41:28

问题


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.

So, my questions are:

  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?

  2. If the declaration int a[4] is within a function, do all the four cells of a get space on stack?


回答1:


  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.

  2. Yes.




回答2:


All local variables, no matter if from built-in types of from classes, or if they are arrays, are on the stack. All dynamic allocations are on the heap.

Of course, modifiers like static on a local variable will make the variable be put somewhere else, so it's preserved between function calls.

Also, to confuse you further, when you create a local pointer variable, and make it point to a dynamically allocated object, e.g.

Class* a = new Class;

The actual variable a is on the stack, but the memory it points to is on the heap.


Addendum: The C++ specification doesn't actually mention anything about stack or heap, only the behavior of different kind of variables.




回答3:


It's exactly the same as with normal types.

Class a; //stack. Usage: a.somethingInsideOfTheObject
Class *a = new Class(); //heap. Usage: a->somethingInsideOfTheObject

Note that if the class itself is allocating something on the heap, that part will always be on the heap, for example:

class MyClass
{
public:
    MyClass()
    {
        a = new int();
    }
private:
    int * a;
};

void foo()
{
    MyClass bar;
}

in this case the bar variable will be allocated on the stack, but the a inside of it will be allocated on the heap.




回答4:


User defined classes (and types) are no different than built-in types. So

Employee emp; // allocated in stack
Employee* emp = new Employee(); // allocated in heap

As for your second question, local arrays are allocated on stack

Employee emp[4]; // 4 instances on stack



回答5:


Generally, if the compiler knows about it at compile time (i.e. local variables), it's on the stack.
If the compiler doesn't know about it at compile time (i.e. dynamic allocation via new, malloc etc), it's on the heap.

This post has a detailed explanation: global-memory-management-in-c-in-stack-or-heap



来源:https://stackoverflow.com/questions/14724390/memory-allocation-for-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!