今天在项目中遇到一个小众的问题,由于不同类的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();
因此写代码了的时候,一旦静态变量之间存在相互依赖的可能就尽量写在方法里面避免不必要的麻烦。希望以上内容对你有帮助!
3773

被折叠的 条评论
为什么被折叠?



