简体   繁体   中英

Where will this be allocated, stack or heap? (C++)

If I have the following code:

class xyzNode
{
public:
    int x;
    int y;
    int z;
    // Other data
};

And in the main I do this:

xyzNode * example = new xyzNode;

I know that the object itself will be allocated on the heap because I'm using the "new" operator, but will the inner variables inside the object also be allocated on the heap? I just wanted to make sure because I'm not using the new operator for them.

Thanks!

The Object (which is just its member variables plus some other information) is going to be placed on the heap, so the member variables will be there as well. The memory for the pointer example however, will be on the stack.

An object's memory consists of its member variables, so those variables will exist in whatever memory block the object was allocated in.

xyzNode * example = new xyzNode;

This allocates a memory block on the heap that is large enough to hold a xyzNode object, then constructs the object within that block, and thus its members exist on the heap.

xyzNode example;

This allocates a memory block on the stack that is large enough to hold a xyzNode object, then constructs the object within that block, and thus its members exist on the stack.

Here is a less common example:

unsigned char buffer[sizeof(xyzNode)];
xyzNode * example = new(buffer) xyzNode;

The members exist on the stack, because placement-new is being used, and it constructs the object within the specified buffer, which is on the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM