Non-local-static variable Initialization

Source: Internet
Author: User

Non-local-static variables, including global objects, objects defined in the namespace scope, objects declared as static within the classes, and objects in the file scope, static variables not included in the function. C ++ does not specify the initialization sequence of non-local-static variables of different compilation units. If these non-local-static variables are mutually dependent, the dependent variables may not be fully initialized. For example

//Month.hclass Month{public:    ~Month(void);    static Month Jan;    static Month Feb;    explicit Month(int a);    int val;};//Month.cpp#include "Month.h"Month Month::Feb(2);Month Month::Jan(1);Month::Month(int a):val(a){}Month::~Month(void){}//MonthTest.h#include "Month.h"class MonthTest{public:    MonthTest(void);    ~MonthTest(void);    Month month;};//MonthTest.cpp#include "MonthTest.h"MonthTest::MonthTest(void):month(Month::Feb){}MonthTest::~MonthTest(void){}MonthTest m_test;//mainextern MonthTest m_test ;int _tmain(int argc, _TCHAR* argv[]){    cout << m_test.month.val <<endl;    getchar();    return 0;}

The output result is 0.

Description month: Feb is not initialized. Because both month: Feb and m_test are non-local-static variables and are defined in different compilation units, m_test depends on month: Feb, and month: Feb is not initialized, such a program has risks.

What to do? Change the non-local-static variable to the local-static variable and return the variable. You can call the function when you need the variable, as shown below:

static Month Jan(){  return Month(1);  }static Month Fet(){   return Month(2);}

In a word, all static variables (including global variables) are defined in the function, that is, all are defined as local-static variables. The non-local-static variable does not exist.

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.