I'm trying to understand POD types and how they are allocated and initialized on the stack. Given
class A {
public:
A();
int x;
};
class B {
public:
int x;
};
int func()
{
A a;
B b;
}
Am I correct in saying that b is allocated after a but initialized prior to a? By that I mean that the space is allocate for a and b in the order that they are declared but b is initialized when the space is allocated and a is initialized when it is declared?
I read a very good FAQ about PODs and Aggregated here What are Aggregates and PODs and how/why are they special?
One of the things he said is: The lifetime of objects of non-POD class type begins when the constructor has finished and ends when the destructor has finished. For POD classes, the lifetime begins when storage for the object is occupied and finishes when that storage is released or reused.
So I'm trying understand the details of how PODs are allocated and initialized and how that is different from non-PODs.
No. a
is allocated and initialized first, and b
is allocated and initialized second. C++ programs are executed statement by statement. Since the memory is automatic, there is no explicit allocation happening anyway -- it's all taken care of automatically.
(For instance, in typical call-stack implementations used on desktop operating systems, the memory is and has always been there and doesn't need to be allocated at all, just addressed.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With