1. A simple single case class:
Class Singleton
{public
:
static Singleton *getinstance ()
{
if (Pinstance_ = = NULL) {
mutex_. Lock ();
if (Pinstance_ = = NULL) {sleep
(1);
Pinstance_ = new Singleton;
}
Mutex_.unlock ();
}
return pinstance_;
}
Private:
Singleton () {}
static Singleton *pinstance_;
Static Mutexlock mutex_;
Singleton *singleton::p instance_ = NULL;
Mutexlock singleton::mutex_;
Mutual exclusion Lock class:
Class Mutexlock
{public
:
mutexlock ()
{
if (Pthread_mutex_init (&lock_, NULL)) {
throw Std::runtime_error ("Init lock fail!");
}
~mutexlock ()
{
if (Pthread_mutex_destroy (&lock_)) {
throw std::runtime_error ("Destroy lock Fail") ;
}
}
void Lock () {
if (Pthread_mutex_lock (&lock_)) {
throw std::runtime_error ("lock failed!");
}
void Unlock () {
if (Pthread_mutex_unlock (&lock_)) {
throw std::runtime_error ("unlock failed!");
}
//Here The pointer is provided for COND wait operation
//This cannot be a const
pthread_mutex_t *getmutexlockptr ()
{return
& Lock_;
}
Private:
pthread_mutex_t lock_;
A simple smart pointer class:
Class Smartptr
{public
:
smartptr (Animal *ptr):p tr_ (PTR)
{
}
~smartptr ()
{
Delete ptr_;
}
Animal *operator-> ()
{return
ptr_;
}
Const ANIMAL *operator-> () const
{return
ptr_;
}
Animal &operator* ()
{return
*ptr_;
}
Const ANIMAL &operator* () const
{return
*ptr_;
}
Private:
disallow_copy_and_assign (smartptr);
T *ptr_;
};
Template <typename t>
class smartptr
{public
:
smartptr (T *ptr = NULL);
~smartptr () {delete ptr_;}
T &operator* () {return *ptr_;}
Const T &operator* () const {return ptr_;}
T *operator-> () {return ptr_;}
Const T *operator-> () const {return ptr_;}
void Resetptr (T *ptr = NULL);
Const T *GETPTR () const {return ptr_;}
Private:
//disable replication and Assignment
smartptr (const smartptr &);
void operator= (const smartptr &);
T *ptr_;
};
Template <typename t>
smartptr<t>::smartptr (T *ptr)
:p tr_ (PTR)
{
}
template <typename t>
void smartptr<t>::resetptr (T *ptr)
{
if (ptr_!= ptr)
{
Delete ptr_ ;
Ptr_ = ptr;
}
}