在主程序中,我dlopen
and dlclose
(LoadLibrary
and FreeLibrary
分别)一个共享库。共享库包含一个实例化的静态变量dlopen
,并销毁于dlclose
。此行为在 MSVC 2008 和 2013、GCC 3.4.6 和 Sunstudio 12.1 上是一致的。
然而,在 GCC 4.9.1 和 GCC 5.2.1 中,不再调用析构函数dlclose
。相反,它是在程序退出之前调用的。
静态变量的类的特殊性在于,在构造函数中,有对模板化函数的调用get(全局范围)返回本地static多变的。
我能够使用链接到共享库的以下一个 cpp 文件重现此行为:
#include <iostream>
template <typename T> // In my actual code, i is of type T, however, this has no effect
int get()
{
static int i = 0;
return i;
}
class Dictionary {
public:
Dictionary()
{
std::cout << "Calling Constructor" << std::endl;
get<int>();
}
~Dictionary(){
std::cout << "Calling Destructor" << std::endl;
}
private:
Dictionary(const Dictionary&);
Dictionary& operator=(const Dictionary&);
};
static Dictionary d;
我研究了可以进行的调整,以便在 dlclose 上调用析构函数,并得出以下结论:
- 如果函数get没有模板化
- else 如果函数中的变量 iget不是静态的
- 否则如果函数get被设为静态
主程序的代码如下:
#include <dlfcn.h>
#include <cassert>
#include <string>
#include <iostream>
void* LoadLib(std::string name)
{
void* libInstance;
name = "lib" + name + ".so";
libInstance = dlopen(name.c_str(), RTLD_NOW);
if ( ! libInstance ) std::cout << "Loading of dictionary library failed. Reason: " << dlerror() << std::endl;
return libInstance;
}
bool UnloadLib(void* libInstance)
{
int ret = dlclose(libInstance);
if (ret == -1)
{
std::cout << "Unloading of dictionary library failed. Reason: " << dlerror() << std::endl;
return false;
}
return true;
}
int main()
{
void* instance = LoadLib("dll");
assert(instance != 0);
assert(UnloadLib(instance));
std::cout << "DLL unloaded" << std::endl;
}
我使用以下命令构建了二进制文件:
g++ -m64 -g -std=c++11 -shared -fPIC dll.cpp -o libdll.so
g++ -m64 -g -std=c++11 -ldl main.cpp -o main.out
在程序退出之前调用析构函数时得到的输出如下:
Calling Constructor
DLL unloaded
Calling Destructor
在 dlclose 上调用析构函数时得到的输出如下:
Calling Constructor
Calling Destructor
DLL unloaded
问题:
- 如果 GCC 版本之间的行为变化不是错误,您能否解释一下为什么 dlclose 上没有调用析构函数?
- 您能否解释一下每个调整:为什么在这种情况下在 dlclose 上调用析构函数?