主程序会依赖一个dll库,单例在dll库中实现,单例的get接口使用dllexport修饰,以便在主程序中获得。
现在发现从主程序第一次调用get和dll库中第一次调用get都会新创建实例。
而后在主程序和dll库中get单例返回的分别是他们第一次创建的实例。代码如下:
dll:test.h
#ifdef EXPORTS
#define dllAPI __declspec(dllexport)
#else
#define dllAPI __declspec(dllimport)
#endif
namespace test:
{
class testclass
{
public:
dllAPI static int* getinstance();
private:
static int* instance;
}
}
dll:test.cpp
#include test.h
namespace test:
{
int* testclass::instance;
int* testclass::getinstance()
{
if(!instance)
instance = new int(0);
return instance;
}
void testclass::function()
{
...
int* g_instance = getinstance();
...
}
}
main:
#include test.h
int main()
{
...
int* g_instance = test::testclass::getinstance();
...
}
不知道这个写法是不是有问题?还是有什么别的需要注意的?