c++ - 使用全局对象时会崩溃,但使用本地对象时不会崩溃

标签 c++ class constructor segmentation-fault

我正在尝试使用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, attribute init_priority can be used to impose a specific ordering.

请参阅 this page 上的构造函数部分了解更多信息。

关于c++ - 使用全局对象时会崩溃,但使用本地对象时不会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47746061/

相关文章:

c++ - 作为其他类成员的依赖类

c++ 没有合适的从 "Camera"到 "Actor *"的转换函数

c++ - 在 Qt Gui 中使用 std::cout

c++ - 继承问题

C++ 将隐式构造限制为特定值

java - 子类构造函数是否需要父类(super class)构造函数的所有参数?

c++ - 用C++做了一个简单的链表,可执行文件太大了?

c++ - 仅黑色窗口绘制三角形,在 MacOS 上使用 openGL 和 GLUT 与 Xcode

jQuery 的 attr - 返回多个类而不仅仅是第一个类

python - 在Python类的另一个函数中获取函数变量