Memory allocation in C++

后端 未结 4 1434
野趣味
野趣味 2020-12-09 06:49

I am confused about the memory allocation in C++ in terms of the memory areas such as Const data area, Stack, Heap, Freestore, Heap and Global/Static area. I would like to u

4条回答
  •  盖世英雄少女心
    2020-12-09 07:18

    I agree with Tomalak,

    C++ does not care where things are stored. It only cares about how they are constructed and destroyed, and about how long they live.

    How it happens, is implementation defined, the compiler might optimize in such a way, that you won't have anything stored on the "stack" when you expect it. The way allocation on the heap happens is defined by the implementation of new/malloc or some third party function (new might call malloc).

    What most likely will happen in your example, is this:

    Foobar bar; // bar will *most likely* be allocated on the "stack".
    Foobar *pBar; // pBar will *most likely* be allocated on the "stack".
    pBar = new Foobar(); // pBar will stay as is, and point to the location on the "heap" where your memory is allocated by new.  
    

    A few things that you might be wondering about. A C-style array, like int array[5] is not stored the same way as a int* pointer= new int[5], the second case will most likely use more memory, since it stores not only the memory for the array, but also memory on the "stack" for the pointer.

    Static constants such as 5 and "cake" are usually stored in a separate .DATA section of the executable.

    The important thing to understand when using C++, most of these things are implementation defined.

提交回复
热议问题