在Linux上,为什么析构函数在C ++中的全局变量的共享实例上运行两次? [英] On Linux, why does the destructor run twice on shared instance of global variable in C++?

查看:287
本文介绍了在Linux上,为什么析构函数在C ++中的全局变量的共享实例上运行两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux上我有一些从定义一个全局变量的静态库生成的C ++代码。这个全局变量的单个实例在引用其符号的两个共享库之间共享。



当进程关闭并运行静态终止阶段时,我看到在这个共享实例上的析构函数运行两次!假设每个图书馆一次卸载一次。



这个问题与我最近看到的另一个问题密切相关:相关问题。这听起来是一样的行为,但是没有讨论为什么会发生。



有没有人知道这个行为背后的理论解释?

解决方案

如果你拿一个赤裸的指针,并将它放在一个智能指针(两次),它会毁灭两次,每次容器refcount降到零。 / p>

因此,如果你将裸指针传递给这两个库,那就可以了。每一个都把它放在一个共享指针对象中,每一个都做了销毁。如果在dtor期间可以看到堆栈回溯,那么应该显示它在两个库中都会发生。


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?

解决方案

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.

这篇关于在Linux上,为什么析构函数在C ++中的全局变量的共享实例上运行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆