第三种方式手动调用destory为啥会造成内存泄漏

因为destroy会把_pInstance置为空,那之后多线程就又都可能走到if里面,走多次new,就会导致内存泄漏

aiexit+pthread_once保证线程安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <pthread.h>

class Singleton{
...
static Singleton * getInstance(){
pthread_once(&_once,init_r);//用该函数来确保init_r来执行多次
//第一个参数固定为一个静态的变量 被初始化为PTHREAD_ONCE_INIT
reutrn _p;
}
static void init_r(){
_pInstance = new Singleton();
atexit(destory);
}
static pthread_once_t _once;
private:
void destory(){
...
}
};
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;

把destory放在public区域手动调用destory会出现段错误 为什么会这样?

因为ptreahd_once确保new Singleton只会执行一次,那么手动destory之后,getInstance返回的就是一个空指针,如果使用该指针来访问具体的数据成员,那么就会发生段错误,因此必须把destory设置为私有的

Init_r也是共有的函数,能否手动调用Init_r呢?

会发生内存泄漏,init_r会又new一份_pInstance,虽然注册了多次destory但是destory会被释放,因为每次新new一个之前指向单例对象区域的指针就被改为新new的那片区域了,之前那一片区域就泄露了