今天在项目中遇到一个小众的问题,由于不同类的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";
然后在主函数中引