• non-local-static 变量的初始化


    non-local-static 变量,包括global对象、定义于namespace作用域内的对象,classes内、以及在file作用域内被声明为static的对象,不包括在函数内的static变量。由于c++对不同编译单元non-local-static 变量的初始化顺序没有规定,如果这些non-local-static变量之间存在相互依赖,则被依赖的变量可能没有完全初始化。如

    //Month.h
    class 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;
    //main
    extern MonthTest m_test ;
    int _tmain(int argc, _TCHAR* argv[])
    {
        cout << m_test.month.val <<endl;
        getchar();
        return 0;
    }

    输出结果0。

    说明Month::Feb并未初始化。因为Month::Feb和m_test都是non-local-static变量,定义在不同的编译单元中,而m_test依赖于Month::Feb,而Month::Feb并未初始化,这样的程序存在风险。

    怎么办,把non-local-static 变量变为local-static变量,并返回该变量,需要变量时调用函数即可,如下

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

    总之,一句话,所有的static变量(包括全局变量)全部放在函数内定义,即都定义为local-static变量。non-local-static变量没有存在的必要。

  • 相关阅读:
    layui 参照赋值的两种方式
    c笔记
    Linux操作系统笔记
    make笔记
    Gcc如何知道文件类型。
    #include <xxx.h>和#include "xxx.h"的区别
    GCC编译流程
    c++ Socket客户端和服务端示例版本三(多线程版本)
    c++ Socket客户端和服务端示例版本二
    c++ Socket客户端和服务端示例版本一
  • 原文地址:https://www.cnblogs.com/clark-lee/p/3870140.html
Copyright © 2020-2023  润新知