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

相关推荐
weixin_4723394622 分钟前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击1 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue2 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
tan180°3 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
m0_555762903 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
浪裡遊4 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
彭祥.4 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
lzb_kkk5 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼5 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
简佐义的博客5 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang