This question already has an answer here:
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?
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:
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.
来源:https://stackoverflow.com/questions/2624880/static-class-variables-in-dynamic-library-and-main-program