Search code examples
c++objectheap-memorynew-operatorstack-memory

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!


Solution

  • 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.