简体   繁体   中英

Understanding the stack in the context of heap objects

Take the simple code below. d is a pointer on the stack that points to a demo object on the heap. The object contains val . This appears to be a stack variable in the context of the class, but the object is allocated on the heap . . . . so where exactly is val ?

class demo
{
    int val;

public:
    demo() : val(5) {};
};

demo* d = new demo();

The variable val is located on the heap, as it is part of an object located on the heap. Each thread has its own stack, but individual objects do not. val would be located on the stack only if d were declared statically.

No matter the object is stored on the stack or heap, val always in the same memory address of demo's object as it's the first member.

§1.8.6

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies . Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses.

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