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

相关推荐
维度攻城狮几秒前
ros2参数通信案例
开发语言·windows·python·ros2·参数通信
清水白石0089 分钟前
Python 与尾递归:为何不优化?如何优雅绕过?
开发语言·python
王大傻092817 分钟前
使用python for循环与ord() + chr()实现字符串加密
开发语言·python
蜕变的土豆18 分钟前
vcpkg使用教程
c++
Louis Maos23 分钟前
堆与栈分配的本质区别
java·开发语言
略无慕艳意1 小时前
C++ 中的 vector
c++
WW_千谷山4_sch1 小时前
洛谷P1120&UVA307 [CERC 1995] 小木棍
c++·算法·深度优先
毕设源码-朱学姐1 小时前
【开题答辩全过程】以 果蔬禽蛋生鲜食品采购配送系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
不要em0啦1 小时前
从0开始学python:函数与数据容器
开发语言·python
zfj3211 小时前
java线程的不同状态下调用interrupt()方法后的行为及注意事项
java·开发语言·interrupt·线程中断·线程状态