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

相关推荐
2401_873479405 小时前
如何利用IP查询定位识别电商刷单?4个关键指标+工具配置方案
开发语言·tcp/ip·php
我爱cope5 小时前
【从0开始学设计模式-10| 装饰模式】
java·开发语言·设计模式
菜鸟学Python5 小时前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
浪浪小洋6 小时前
c++ qt课设定制
开发语言·c++
charlie1145141917 小时前
嵌入式C++工程实践第16篇:第四次重构 —— LED模板,从通用GPIO到专用抽象
c语言·开发语言·c++·驱动开发·嵌入式硬件·重构
handler017 小时前
Linux: 基本指令知识点(2)
linux·服务器·c语言·c++·笔记·学习
故事和你917 小时前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
程序猿编码7 小时前
给你的网络流量穿件“隐形衣“:手把手教你用对称加密打造透明安全隧道
linux·开发语言·网络·安全·linux内核
aq55356008 小时前
编程语言三巨头:汇编、C++与PHP大比拼
java·开发语言
aq55356008 小时前
PHP vs Python:30秒看懂核心区别
开发语言·python·php