xiaoxiangyue_lib 2018-04-23 12:01 采纳率: 0%
浏览 2603
已结题

一个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();
    ...
}

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

  • 写回答

5条回答 默认 最新

  • oyljerry 2018-04-23 12:11
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题