我正在尝试创建一个简单的 Win32 DLL。作为 DLL 和 EXE 之间的接口(interface),我使用 C 函数,但在 DLL 内部我使用 C++ 单例对象。以下是我的 DLL 实现的示例:
//MyDLLInterface.cpp 文件 --------------------------------
#include "stdafx.h"
#include <memory>
#include "MyDLLInterface.h"
class MySingleton
{
friend class std::auto_ptr< MySingleton >;
static std::auto_ptr< MySingleton > m_pInstance;
MySingleton()
{
m_pName = new char[32];
strcpy(m_pName, “MySingleton”);
}
virtual ~ MySingleton()
{
delete [] m_pName;
}
MySingleton(const MySingleton&);
MySingleton& operator=(const MySingleton&);
public:
static MySingleton* Instance()
{
if (!m_pInstance.get())
m_pInstance.reset(new MySingleton);
return m_pInstance.get();
}
static void Delete()
{
m_pInstance.reset(0);
}
void Function() {}
private:
char* m_pName;
};
std::auto_ptr<MySingleton> MySingleton::m_pInstance(0);
void MyInterfaceFunction()
{
MySingleton::Instance()->Function();
}
void MyInterfaceUninitialize()
{
MySingleton::Delete();
}
//MyDLLInterface.h 文件 --------------------
#if defined(MY_DLL)
#define MY_DLL_EXPORT __declspec(dllexport)
#else
#define MY_DLL_EXPORT __declspec(dllimport)
#endif
MY_DLL_EXPORT void MyInterfaceFunction();
MY_DLL_EXPORT void MyInterfaceUninitialize();
我遇到的问题如下:如果我不从我的 EXE ExitInstance() 调用 MyInterfaceUninitialize() ,我有内存泄漏(m_pName 指针)。为什么会发生这种情况?看起来 MySingleton 的破坏发生在 EXE 退出后。是否可以强制 DLL 或 EXE 提前一点销毁 MySingleton,这样我就不需要调用 MyInterfaceUninitialize() 函数?
编辑: 感谢您的所有帮助和解释。现在我明白这是一个设计问题。如果我想继续使用当前的解决方案,我需要在 EXE 中调用 MyInterfaceUninitialize() 函数。如果我不这样做,也没关系,因为当单例离开 EXE 范围时,它会自行销毁(但我需要忍受令人不安的调试器消息)。避免这种行为的唯一方法是重新考虑整个实现。
我还可以在 Visual Studio 中的“链接器”->“输入”下将我的 DLL 设置为“延迟加载的 DLL”,以消除令人不安的调试器消息。
最佳答案
If i don't call MyInterfaceUninitialize() from my EXEs ExitInstance(), i have a memory leak (m_pName pointer). Why does it happening?
这不是泄漏,这是 auto_ptr 应该工作的方式。当它们超出范围时(在您的情况下是当 dll 被卸载时),它们会释放实例。
It looks like the destruction off MySingleton happens after EXEs exit.
是的。
Is it possible to force the DLL or EXE to destroy the MySingleton a little bit earlier, so I don't need to call MyInterfaceUninitialize() function?
没有调用这个函数就不行。
关于c++ - DLL中单例的销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1643690/