In C + +, there are four ways to produce an object.
The first method is generated in the stack:
void MyFunc ()
{
Cfoo foo;//to generate Foo object in stacks (stack)
}
The second method is to generate it in the heap:
void MyFunc ()
{
cfoo* pfoo=new Cfoo ();//Generate Objects in heap
}
The third method is to produce a global object (and also necessarily a static object)
Cfoo foo;//do this outside of any function scope
The fourth method is to produce a local static object
void Cmyfunc ()
{
Static Cfoo foo;//a golden Thai object within the range of the function
}
Either way, C + + produces a call operation against the Cfoo constructor.
In the first two cases, C + + immediately generates a hidden constructor call after the memory is configured.
In the third case, there is obviously no place for such a constructor call operation because the object is implemented outside of any function activity scope. The third case of the constructor call operation must rely on the startup code to help. Startup is code that executes earlier than the program entry point (main or WinMain), which is provided by the C + + compiler and is linked to the program. Startup code might do things like function library initialization, process information setup, I/O stream generation, and initialization of a static object (that is, calling its constructor). When the compiler compiles your program and discovers a static object, it adds the object to a list and adds a pointer to the object's constructor and its arguments. Before handing control over to the program entry point, the Starup code iterates through the list, invokes all the enlisted constructors and parameters, and initializes the static object.
The fourth case (local static object) will only have one instance generated, and in fixed memory (neither stack nor heap). Its constructor is called when control is first transferred to its declaration (that is, when MyFunc is first called).
C + + Four different kinds of object survival methods