动态库和主程序中的静态类变量
我正在开发一个项目,该项目有一个类“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题已经在我发布的另一个问题中得到解决。基本上,静态变量确实有两个副本——一份在主程序中,一份在共享库中,但运行时链接器将这两个副本解析为主程序副本。有关更多信息,请参阅此问题:
主要程序和共享库在 __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
我相信 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.