C++单例模式跨DLL调用问题梳理

问题案例:

假设有这样一个单例模式的代码

cpp 复制代码
//test.h header
class Test
{
public:
	static Test &instance() 
	{
		static Test ins;
		return ins;
	}
	void foo();
};

void testFoo();
cpp 复制代码
//test.cpp source
#include "test.h"

void Test::foo()
{
	printf("%p\n", this);
}
void Bar()
{
	Test::instance().foo();
}

接下来分别调用它们

cpp 复制代码
#include "test.h"

int main()
{
	Bar();
	Test::instance().foo();
	return 0;
}

运行后得到结果

cpp 复制代码
>./main
>00007ff8c63a8110
>00007ff664923100

居然得到了不一样的地址,说明这种方法实现单例会发生意料之外的问题。

通过网上检索后终于知道:由于static变量是单个编译单元的变量,当dll代码中的头文件定义static变量时并且main函数调用时,ins变量实际已经被认为是两个静态变量了(个人猜想:编译器为了区分变量,可能会隐式添加后缀用于区分),因此在main中调用Test::instance().foo()时,实际是在第一次构造属于主程序单元内的ins静态变量。

解决办法

1.将instance实现方法写到cpp中

将static变量的定义写到cpp中,则不会在dll中编译时标记ins为静态变量,确保了其唯一性。

cpp 复制代码
//test.cpp source
#include "test.h"

Test &Test::instance()
{
	static Test ins;
	return ins;
}

2.手写一个管理类

在某乎看到大佬写的,其原理是将所有获取单例的方法集合在一起,但需要注意它不满足支持热卸载的动态库,因为是管理的指针

https://github.com/KondeU/GlobalSingleton/tree/master

相关推荐
阿里嘎多学长3 小时前
2026-02-16 GitHub 热点项目精选
开发语言·程序员·github·代码托管
啊吧怪不啊吧4 小时前
C++之基于正倒排索引的Boost搜索引擎项目usuallytool部分代码及详解
开发语言·c++·搜索引擎·项目
CeshirenTester4 小时前
9B 上端侧:多模态实时对话,难点其实在“流”
开发语言·人工智能·python·prompt·测试用例
发现你走远了4 小时前
Windows 下手动安装java JDK 21 并配置环境变量(详细记录)
java·开发语言·windows
游乐码5 小时前
c#类和对象
开发语言·c#
黎雁·泠崖5 小时前
Java常用类核心详解(一):Math 类超细讲解
java·开发语言
懒惰成性的6 小时前
12.Java的异常
java·开发语言
-To be number.wan6 小时前
Python数据分析:时间序列数据分析
开发语言·python·数据分析
前路不黑暗@6 小时前
Java项目:Java脚手架项目的通用组件的封装(六)
java·开发语言·spring
马士兵教育6 小时前
程序员简历如何编写才能凸显出差异化,才能拿到更多面试机会?
开发语言·后端·面试·职场和发展·架构