On Linux, why does the destructor run twice on shared instance of global variable in C++?

一笑奈何 提交于 2019-12-08 18:33:20

问题


On Linux I have some generated C++ code from a static library that defines a global variable. A single instance of this global variable is shared between two shared libraries that refer to its symbol.

When the process shuts down and the static termination phase is run, I see that the destructor on this shared instance is run twice! Presumably once per library as each unloads.

This question is closely related to another I saw recently here: related question. This sounds like the same behavior, but there is no discussion about why it is happening.

Does anybody know the theoretical explanation behind this behavior?


回答1:


If you take a naked pointer and place it in a smart pointer (twice), it will destruct twice, once for each container refcount falling to zero.

So, if you pass the naked pointer into both libraries, that would do it. Each one puts it in a shared pointer object and each of those does the destruction. If you can see the stack backtrace during the dtor, that should show it happening in both of the libraries.




回答2:


C++ has a rule called the "One Definition Rule":

Every program shall contain exactly one definition of every non-inline function or object that is used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see 12.1, 12.4 and 12.8).

Wikipedia has an article that explains this in more detail.

You haven't posted code in your question, so I can't be sure about your case, but in the question you linked to, the example in the question was defining the same variable in two shared libraries. This violated the "One Definition Rule", which apparently the dynamic linker's finalization strategy depends on, causing the destructor to be called twice.



来源:https://stackoverflow.com/questions/3409034/on-linux-why-does-the-destructor-run-twice-on-shared-instance-of-global-variabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!