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

相关推荐
千里马-horse7 小时前
AsyncContext
开发语言·前端·javascript·c++·napi·asynccontext
Coder_Boy_7 小时前
基于MQ实现秒杀订单系统的异步化架构
java·开发语言·架构
勇往直前plus7 小时前
Jackson 反序列化首字母大写字段映射失败的底层原因与解决方案
java·开发语言·前端
坐吃山猪7 小时前
Python命令行工具Click
linux·开发语言·python
宠..7 小时前
为单选按钮绑定事件
运维·服务器·开发语言·数据库·c++·qt·microsoft
咋吃都不胖lyh8 小时前
在任务管理器中筛选、查看进程
java·开发语言
宠..8 小时前
对单选按钮分组
开发语言·数据库·c++·qt·安全·安全性测试
大学生资源网8 小时前
基于JavaWeb的邮件收发系统的设计与实现(源码+文档)
java·开发语言·spring boot·mysql·毕业设计·源码·课程设计
cici158748 小时前
基于高斯混合模型(GMM)的说话人识别系统MATLAB实现
开发语言·人工智能·matlab
崇山峻岭之间8 小时前
Matlab学习记录11
开发语言·学习·matlab