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

相关推荐
浅时光_c3 分钟前
9 循环语句
c语言·开发语言
stevenzqzq4 分钟前
Kotlin 协程:withContext 与 async 核心区别与使用场景
android·开发语言·kotlin
CDN36012 分钟前
弱网下游戏盾掉线重连失败?链路保活与超时参数优化
开发语言·游戏·php
im_AMBER12 分钟前
Leetcode 153 课程表 | 腐烂的橘子
开发语言·算法·leetcode·深度优先·图搜索
paeamecium13 分钟前
【PAT甲级真题】- Reversing Linked List (25)
数据结构·c++·算法·pat
烈风17 分钟前
01_Tauri环境搭建
开发语言·前端·后端
cch891817 分钟前
PHP爬虫框架大比拼
开发语言·爬虫·php
TTTrees21 分钟前
C++学习笔记(38):封装、继承、多态
c++
l1t24 分钟前
DeepSeek辅助编写的dmp转schema和csv文件c语言程序
c语言·开发语言·windows
6Hzlia27 分钟前
【Hot 100 刷题计划】 LeetCode 54. 螺旋矩阵 | C++ 模拟法题解
c++·leetcode·矩阵