一个static变量出现两个实例,单例模式出现了两个实例

主程序会依赖一个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();
    ...
}

不知道这个写法是不是有问题?还是有什么别的需要注意的?

你创建单例判断指针等没意见加锁。以及双层空指针判断。

你有用到多线程么?如果有,需要对
if(!instance)
instance = new int(0);
这里做同步。

另外,dll是每个进程实例一份的,不可以用这个代码实现跨进程的单例,如果你要所有进程单例,需要用互斥量来实现。

consolog 没有清屏 你试试

你的instance这个没有初始化啊。

单例模式需要优化,double check能解决出现其他实例的问题
标准线程安全的单例代码演示