C + + compiled successfully, failed to run the static variable

Source: Internet
Author: User

First look at a piece of code:

///////////////////////////////////////////////////// class   Single{Public :     Single(); Static Single* S_INST; Staticstd:: Map<int, int> S_map;}; Single* S_inst = new Single;std:: Map<int, int>Single ::S_map;Single::single() {s_map[4] =6;}

The above code can be compiled using both MinGW492 and VS2008, but will report errors when running. is an error when using MinGW492:

原因就在于类Single中有两个静态成员变量static Single* s_inst;staticstd::map<int, int> s_map;

Static variables must be initialized before entering the main function.
The sequence of initialization of static variables is consistent with the order in which they are defined, regardless of the order in which they are declared .

The order of the definitions is:

new Single;std::map<int, int> Single::s_map;

Therefore, the single constructor is entered, and the S_map is inserted in the single constructor, and S_map is not initialized at this time.

So the modification method is also very simple, modify the order of the static variable definition:

///////////////////////////////////////////////////// class   Single{Public :     Single(); Static Single* S_INST; Staticstd:: Map<int, int> S_map;};//S_map before S_inststd:: Map<int, int>Single ::S_map; Single* S_inst = new Single;Single::single() {s_map[4] =6;}

To say more, this article does not discuss the singleton pattern, the case of a single example is later written.

C + + compiled successfully, failed to run the static variable

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.