Timing of constructing c ++ global objects by Mr. Swiss

Source: Internet
Author: User

First look at the code: [cpp] # include <windows. h ># define showdbg (str) \{\ MessageBoxA (0, # str, "", 0) ;\}; class A {public: () {showdbg ("fuckme ");}~ A () {showdbg ("end") ;}void dosomething () {showdbg ("something") ;}}; A a; void main () {. if the default compilation and link method is used, the result is three message boxes. But I want to see how the Global Object a is initialized. Compile: cl/c/ehsmsg. cpp link: link/entry: main/subsystem: windows/nodefaultlib msg. obj error: the system prompts that the cause of _ atexit is not found. The Global object is not initialized without reason before the real main function. It needs to use atexit In the crt function to register some functions (possibly destructor) and then use the normal compilation method: cl msg. cpp generates msg.exe and observes it in the debugger. It is found that the initialization process of the global object is as follows: In the CRT, msvcrt. dll calls the _ pre_cpp_init function in the default Library (/nodefaultlib) of the linker (this function will be compiled into your program by default ). Just so. Therefore, the global object mentioned in the book will be automatically constructed before the MAIN function, which is actually incorrect. It is not automatically constructed, it is done by CRT for you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.