解决静态全局变量初始化的相互依赖问题

今天在项目中遇到一个小众的问题,由于不同类的static变量初始化之间存在着相互的依赖导致segment default。

为了描述问题本身,我用一个简单的例子来说明。如代码所示类A中有一个static的string变量a:

#ifndef A_H
#define A_H
#include <iostream>
 
 class A
 {
  public:
          static std::string  a;
  };

#endif
同样类B也有一个static的string变量b

#ifndef B_H
#define B_H
#include <iostream>
 
 class B
 {
  public:
          static std::string  b;
  };

#endif

在A.cpp中类A的static string的初始化需要用类B的string b变量。代码如下:

#include "B.h"
#include "A.h"
std::string  A::a=B::b;
在类B中对b进行初始化。代码如下:
#include "B.h"
std::string B::b="helloworld";
然后在主函数中引用两个string对象:
#include "A.h"
#include "B.h"

using namespace std;

int main()
{
     cout<<A::a<<endl;
     cout<<B::b<<endl;
     return 0
}

按如下方式编译源代码: g++ *.cpp -o test

在执行test的时候会报segment default。原因是初始化A的静态变量的时候需要用到B类的静态变量,而此时B类的变量还没来得及分配内存和初始化,因此会报segment default。可以通过改变链接顺序来避免该错误,即先 g++ *.cpp -c 

然后 g++ B.o A.o main.o -o test。


如果是一个小的demo只有几个文件,那么可以这么做。但是项目如果是通过makefile来写的,链接的顺序是编译器自动解析的(或者文件过多,也不能人为分析复杂的依赖关系),那么就不能这样解决了。

解决上述问题的方法是将变量的初始化放到static函数里面进行,因为函数的注册要早于变量。代码如下:

#ifndef A_H
#define A_H
#include <iostream>
 
 class A
 {
  public:
          static std::string  a;
  };

#endif

#ifndef B_H
#define B_H
#include <iostream>
class B
{
       public:
           static std::string& get_b()
           {
<span style="white-space:pre">	</span>//为了保证只分配一次内存,因此写成了static,
<span style="white-space:pre">	</span>//不是static也可以,不过就不要返回引用了
              static std::string temp="helloworld";
              return temp;
          }
};
#endif


#include "B.h"
#include "A.h"
std::string  A::a=B::get_b();


于是无论编译器链接顺序如何,程序都能正常工作了。

因此写代码了的时候,一旦静态变量之间存在相互依赖的可能就尽量写在方法里面避免不必要的麻烦。希望以上内容对你有帮助!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值