开发者

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

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开发者_JAVA技巧.

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜