Stack allocation of a user-defined class object

I am trying to understand the types of POD and how they are allocated and initialized on the stack. Considering,

class A { public: A(); int x; }; class B { public: int x; }; int func() { A a; B b; } 

Am I saying correctly that b stands out after, but initializes to a? By this I mean that the space is allocated for a and b in the order in which they are declared, but b is initialized when the space is allocated and a is initialized when it is declared?

I read the very good POD FAQ and compiled here What are aggregates and PODs and how / why are they special?

One of the things he said: The lifetime of non-POD class objects begins when the constructor completes and finishes working with the completion of the destructor. For POD classes, the lifetime begins when the storage for the object is busy and ends when this storage is released or reused.

So, I'm trying to understand the details of how PODs are allocated and initialized, and how they are different from non-PODs.

+4
source share
3 answers

No. a first allocated and initialized, and b is allocated and initialized by the second. C ++ programs run on request. Since the memory is automatic, in any case, no explicit distribution occurs - all this will be taken care of automatically.

(For example, in typical implementations of the call stack used on desktop operating systems, memory has always been and should not be allocated at all, just addressed.)

+9
source

You have zero guarantees of any order for the order in memory that A and B are allocated.

If A and B had constructors, a is called before b. But the POD types you are asking about (and which are B) are not initialized at all with this syntax, so the question is debatable.

The issue of initializing the object as to when the storage is allocated does not make much sense anyway. For example, most compilers here will allocate space for A and B in the same stack pointer. Given that the corresponding C ++ program cannot detect such a thing (what does this even mean?), The Compiler can do whatever it wants.

+2
source

These are local variables, they are not "distributed" in common sense, you can simply consider them to be there. (As it remains to implement, the general way is to use the stack supported by the processor. In this case, all storage for all local objects is pushed onto the stack when writing the function).

Initialization always occurs in the order of declarations. Here, this means that A :: A () is called for a, then B :: B () is called for b.

0
source

Source: https://habr.com/ru/post/1486872/


All Articles