Can I replace code in main() into a constructor of a global object?
Assuming that init
is the last global object being initialized before main()
(and we don't need any command line argument), can I do something like:
struct int_main {
int_main ()
{
//... start code execution
}
}init;
int main ()
{
}
Asking the question in this way, because I am interested in knowing开发者_StackOverflow if main()
assures anything other than:
- argc, argv from command line
- All global objects are initialized before it
You do not have a guarantee that all global objects are constructed before your object, so you may not use any of them. That includes vital parts of iostreams.
I normally use the pattern that main()
just constructs the application object and invokes a method on it to perform the actual work.
You would have a hard time catching any exception from the int_main
constructor.
Also you would have a hard time returning a process exit code with complete unwinding of the stack.
That's mainly what main
provides in C++: a place to catch exceptions, and a means to return normally (not just exit
) with a specified process exit code.
Cheers & hth.,
Within C\C++ you can declare the entry point of your application via the visual studio IDE. It's the convention that the entry point into you're code will be either be Main or in the case of a win32 exe WinMain.
As to answer your question, the CRT will iniailize all global variables in the order of
C Primitive Types
C Struct Types and or C++ Class types
Call the class constructors
Call the Entry point into your application, this will be done from CRTStartup (correct me if i'm wrong)
In theory this is possible, but you're not assured of the initialization order of global objects, so you are not going to have an assurance of which object will be initialized last, and therefore you're going to have a problem with running a "main" inside a global object that may not have the proper state of the program setup before its constructor is called. Furthermore, you're not going to be capable of suspending the execution of your "main" object's constructor to wait for the proper starting state to exist if such a scenario occurs.
Additionally, since the OS's runtime will be calling your actual main()
function in order to actually "run" your program regardless of the presence of a "main" global object or not, you're going to need to return a value from 'main()` in order for the OS runtime to determine the exit status of your program.
精彩评论