Reputation: 612
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.
Upvotes: 4
Views: 243
Reputation: 17163
These are local variables, they are not "allocated" in the common sense, you can just consider them being there. (How is left to implementation; common way is to use a processor-supported stack. In that case all the storage for all local objects is taken on the stack at function entry).
Initialization always happens in the order of declarations. Here it means A::A() is called for a, then B::B() is called for b.
Upvotes: 0
Reputation: 71969
You have zero guarantees of any kind for the order in memory that A and B are allocated.
If A and B both had constructors, a's would be called before b's. But POD types, which you're asking about (and which B is) are not initialized at all with this syntax, so the question is moot.
The question of object initialization in relation to when the storage is allocated doesn't make much sense anyway. For example, most compilers here will allocate space for A and B in a single stack pointer move. Given that there is no way a conforming C++ program can detect such a thing (what does it even mean?), the compiler can do pretty much whatever it wants, though.
Upvotes: 2
Reputation: 477030
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.)
Upvotes: 9