本文主要是介绍实现“带寿命的Singletons”,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
鸡生蛋、蛋生鸡问题不必纠结,只需要仔细操控PTrackerArray,看代码
namespace Private{
class LifetimeTracker{
public:
LifetimeTracker(unsigned int x):longervity__(x){}
vitual ~LifetimeTracker()=0;
friend inline bool Compare(
unsigned int longevity,const LifetimeTraker *p)
{
return p ->longevity_<longevity;
}
private:
unsigned int longevity_;
}
inline LifetimeTracker::~LifetimeTracker(){}
}
namespace Private{
typedef LifetimeTracker ** TrackerArray;
extern TrackerArray pTrackerArray;
extern unsigned int elements;
}
template <typename T>void Delete(T *pObj)
{
delete pObj;
}
namespace
{
template <typename T,typename Destroyer>
class ConcreteLifetimeTracker: public LifetimeTracker
{
public:
ConcreateLifetimeTracker(T* pDynObject,unsigned int longevity,Destroyer destroyer):
LifetimeTracker(longevity),pTracked_(pDynObject),
destroyer_(destroyer)
{}
~ConcreteLifetimeTracker()
{
destroyer_(pTracked_);
}
private:
T *pTracked_;
Destroyer destoryer_;
};
void AtExitFn();
}
template <typename T,typename Destoryer>
void SetLogevity(T *pDynObject ,unsigned int longevity,Destroyer d = Private::Deleter<T>::Delete)
{
TrackerArray pNewArray = static_cast<TrackerArray>(std::realloc(pTrackerArray,sizeof(T)*(elements+1)));
if(!pNewArray)throw std::bad_alloc();
pTrackerArray= pNewArray;
LifetimeTracker *p=new ConcreateLifetimeTracker<T,Destroyer>(pDynObject,longevity,d);
TrackerArray pos = std::upper_bound(pTrackerArray,pTrackerArray+elements,longevity,Compare);
std::copy_backward(pos,pTrackerArray+elements,pTrackerArray+elements+1);
*pos =p;
++elements;
std::atexit(AtExitFn);
}
static void AtExitFn()
{
assert(elements>0&&pTrackerArray !=0);
LifetimeTracker * pTop= pTrackerArray[elemets -1];
pTrackerArray= static_cast<TrackerArray>(std::realloc)(pTrackerArray,sizeof(T)*--elements));
delete pTop;
}
class Log
{
public :
static void Create()
{
pInstance_=new Log;
SetLongevity(*this,longevity_);
}
private:
static const unsigned int longevity_=2;
static Log*pInstance_;
}
多线程处理Singleton
Single& Singleton::Instance()
{
if(!pInstance_)
{
Lock guard(mutex_);
pInstance_=new Singleton;
}
return *pInstance_;
}
这篇关于实现“带寿命的Singletons”的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!