我正在尝试使用libconfig为我的程序创建配置文件。有两种情况,一种可以完美运行(本地范围对象),另一种则失败(全局范围对象)。我试图理解为什么一个失败而另一个成功,因为我的理解是两者都是创建相同对象的定义(只是在不同的范围内)。
第一个(不起作用):我在全局范围内定义了一个 Config 对象。然后我对 Config 对象调用 readFile。程序在这里崩溃了。
#include <libconfig.h++>
libconfig::Config cfg;
int __attribute__((constructor)) Init()
{
cfg.readFile("/home/jalius/csgo-internal/hack.cfg");
}
第二(有效):我定义一个本地 Config 对象并对其调用 readFile。
#include <libconfig.h++>
int __attribute__((constructor)) Init()
{
libconfig::Config cfg;
cfg.readFile("/home/jalius/csgo-internal/hack.cfg");
}
最佳答案
当您调用 int __attribute__((constructor)) Init()
函数时,在您的情况下,不会创建 cfg
对象。因为使用属性constructor
修饰的函数和具有静态存储持续时间的C++对象的调用顺序是未指定的。由于对象不存在,因此您会收到段错误错误,即 SIGSEGV
信号。
以下是摘自 GCC website :
at present, the order in which constructors for C++ objects with static storage duration and functions decorated with attribute
constructor
are invoked is unspecified. In mixed declarations, attributeinit_priority
can be used to impose a specific ordering.
请参阅 this page 上的构造函数
部分了解更多信息。
关于c++ - 使用全局对象时会崩溃,但使用本地对象时不会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47746061/