开发者

Static Class Variables in Dynamic Library and Main Program [duplicate]

开发者 https://www.devze.com 2022-12-26 07:45 出处:网络
This question already has an answer here: Main Program and Shared Library initializes same static variable in __static_initialization_and_destruction_0
This question already has an answer here: Main Program and Shared Library initializes same static variable in __static_initialization_and_destruction_0 (1 answer) Closed 4 years ago.

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.

开发者_JS百科

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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消