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

相关推荐
浪客川12 小时前
rust入门案例-猜数字游戏
开发语言·rust
草莓熊Lotso12 小时前
C++ 智能指针完全指南:原理、用法与避坑实战(从 RAII 到循环引用)
android·java·开发语言·c++·人工智能·经验分享·qt
羑悻的小杀马特12 小时前
零成本搭建个人音乐库,香橙派 Zero3 部署 Melody 配合 CPolar 实现外网畅听
c++·ai·cpolar
bbq粉刷匠12 小时前
Java基础语法问答
java·开发语言·python
龙智DevSecOps解决方案12 小时前
汽车网络安全开发语言选型指南:C/C++/Rust/Java等主流语言对比+Perforce QAC/Klocwork工具支持
开发语言·autosar·嵌入式开发·perforce·代码安全·汽车网络安全
Eiceblue13 小时前
将 Python 列表导出为 Excel 文件:一维、二维、字典列表
开发语言·python·excel·visual studio code
qq_4663024520 小时前
vs2008 Hotlink实时数据读取
c++·qt
代码or搬砖20 小时前
String字符串
android·java·开发语言
阿达King哥20 小时前
关于C++中的typedef typename的含义
c++