动态库和主程序中的静态类变量

发布于 2024-08-28 18:40:15 字数 383 浏览 14 评论 0原文

我正在开发一个项目,该项目有一个类“A”,其中包含静态 stl 容器类。此类包含在我的主程序和 .so 文件中。该类使用默认(隐式,未声明)构造函数/析构函数。主程序使用 dlopen() 加载 .so 文件,并在其析构函数中调用 dlclose()。当glibc调用静态类成员变量的析构函数时,main退出后程序崩溃。问题似乎是当调用 dlclose() 时,调用静态变量的析构函数,然后当 main exits() glibc 也调用析构函数,导致双重释放。

我有 2 个问题,即:
1)在这种特殊情况下,为什么没有静态变量的两个副本(是的,我知道这听起来有点荒谬,但由于主程序和.so文件都有一个单独编译的“A”,它们不应该都有一个?)
2)有没有办法解决这个问题,而无需重写类“A”以不包含静态成员变量?

I am working on a project that has a class 'A' that contains a static stl container class. This class is included in both my main program and a .so file. The class uses the default(implicit, not declared) constructor/destructor. The main program loads the .so file using dlopen() and in its destructor, calls dlclose(). The program crashes after main exits when glibc calls the destructor for the static class member variable. The problem appears to be that when dlclose() is called, the destructor for the static variable is called, then when main exits() glibc also calls the destructor, resulting in a double free.

I have 2 questions, namely:
1) In this particular case, why are there not two copies of the static variable(yes i know that sounds somewhat ridiculous, but since both the main program and .so file have a separately compiled 'A', shouldn't they each have one?)
2) Is there any way to resolve this issue without re-writing class 'A' to not contain static member variables?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

画骨成沙 2024-09-04 18:40:15

这个问题已经在我发布的另一个问题中得到解决。基本上,静态变量确实有两个副本——一份在主程序中,一份在共享库中,但运行时链接器将这两个副本解析为主程序副本。有关更多信息,请参阅此问题:

主要程序和共享库在 __static_initialization_and_destruction_0 中初始化相同的静态变量

This question has been resolved in another question I posted. Basically there were indeed two copies of the static variable -- one in the main program and one in the shared library, but the runtime linker was resolving both copies to the main programs copy. See this question for more information:

Main Program and Shared Library initializes same static variable in __static_initialization_and_destruction_0

咿呀咿呀哟 2024-09-04 18:40:15

我相信 STL 类总是动态创建的,因此您实际上不能将它们称为静态类。它们存在于堆上。如果将该成员传递给函数,则将副本放入静态内存中。您必须创建自己的析构函数来显式删除 stl 一次。

I believe that STL classes are always dynamically created so you can't actually call them static. They exist on the heap. If the member is passed to a function then a copy is put into static memory. You have to make your own destructor that deletes the stl explicitly once.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文