C++单例模式中存在static instance资源什么时间被回收的问题

本文探讨了C++单例模式中static实例何时会被回收的问题,并提出使用shared_ptr作为解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class CSingleton
{
private:
	CSingleton()   //构造函数是私有的
	{
	}
	static CSingleton *m_pInstance;
public:
	static CSingleton * GetInstance()
	{
		if(m_pInstance == NULL)  //判断是否第一次调用
			m_pInstance = new CSingleton();
		return m_pInstance;
	}
};

使用shared_prt来解决这个问题

// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<memory>

using namespace std;

class B
{
public :
	B(int  b){ _b = b; }
	int _b;
	~B()
	{
		cout << "释放B"<< _b << endl;
	}
};


class Singleton
{

public:
	~Singleton()
	{
		cout << "释放singleton" << endl;
	}
private:
	Singleton(){ 
		
	};
private:
	static shared_ptr<Singleton> _instance;

public:
	static shared_ptr<Singleton> getInstance();

	void printCode()
	{
		cout << "i am printing" << std::endl;
	}

	vector<B*> bs;
	
};

shared_ptr<Singleton>  Singleton::_instance = nullptr;


shared_ptr<Singleton>  Singleton::getInstance()
{
	 
	if (_instance == nullptr)
		_instance =  shared_ptr<Singleton>(new Singleton());
	return _instance;
	 
}


void testSingleton()
{
	auto s = Singleton::getInstance();
	B b3 (3);
	s->bs.push_back(&b3);  //b3 出函数后会被销毁,所以出了该作用域之后的b调用会有大问题
	for each (auto var in s->bs)
	{
		cout << var->_b << endl;
	}
	
}


int _tmain(int argc, _TCHAR* argv[])
{

	shared_ptr<Singleton>  s = Singleton::getInstance();
	s->printCode();


	B b1 = B(1);
	B b2 = B(2);
	testSingleton();

 
	s->bs.push_back(&b1);
	s->bs.push_back(&b2);

	for each (auto var in s->bs)
	{
		cout << var->_b << endl;
	}


	
	return 0;// Main函数调用结束之后 Singleton的实例会被回收,其资源也会被回收


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值