📄 janitor.h
字号:
////////////////////////////////////////////////////////////////////////////////
// 指针看门人
////////////////////////////////////////////////////////////////////////////////
// Author : Darkay Li
// Description : 看守指针,在析构的时候删除指针。兼容auto_ptr的部分方法
// 如:get(),release(),对非数组形式指针的operator *,->
//
// Version : 1.0
//
// Standard include files :
//
// Start Date : 2003年5月9日
//
// Change Log :
// 2003年5月9日 by Darkay Li
// -- Created
// 2003年5月15日 by Darkay Li
// -- add some notes, remove the code in .cpp, add to ClearCase
////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_JANITOR_H
#define INCLUDED_JANITOR_H
#if defined(HAS_PRAGMA_ONCE)
#pragma PRAGMA_ONCE_DECLARE
#endif
namespace stk
{
#pragma warning(disable:4284)
//pointer janitor
//delete the memory when need
template<class T>
class Janitor
{
public:
//ctor
//@param -- pointer to be guard
Janitor(T* const toDelete)
: m_pointer(toDelete)
{
}
//dtor
~Janitor()
{
reset();
}
//don't guard anymore, user must hold the pointer themselves
void orphan()
{
release();
}
//compatibility @std::auto_ptr
//dereference operator
T& operator*() const
{
return *m_pointer;
}
//compatibility @std::auto_ptr
//pointer operator
T* operator->() const
{
return m_pointer;
}
//get the pointer
T* get() const
{
return m_pointer;
}
//set the internal pointer to nil
//and return the pointer to user
T* release()
{
T *p = m_pointer;
m_pointer = 0;
return p;
}
private:
//delete the pointer and set it with another
void reset(T *other = 0)
{
delete m_pointer;
m_pointer = other;
}
//forbid no parameter ctor and default ctor
Janitor();
//forbid copy
Janitor(const Janitor&);
private:
//hold the pointer
T* m_pointer;
};
//guard array pointer
//just like the Janitor but it guard the pointer which create by "new [xxx]"
//and it will delete the pointer by "delete []"
template<class T>
class ArrayJanitor
{
public:
ArrayJanitor(T* const toDelete)
: m_array(toDelete)
{
}
~ArrayJanitor()
{
reset();
}
void orphan()
{
release();
}
//get index value reference,
T& operator[](size_t index) const
{
return m_array[index];
}
T* get() const
{
return m_array;
}
T* release()
{
T* p = m_array;
m_array = 0;
return p;
}
private:
void reset(T* other = 0)
{
delete []m_array;
m_array = other;
}
//forbid default ctor
ArrayJanitor();
//forbid copy
ArrayJanitor(const ArrayJanitor& );
private:
T* m_array;
};
template<class OBJECT, class ACTION>
class ActionJanitor
{
public:
ActionJanitor(OBJECT &obj, ACTION &act)
: m_object(obj)
, m_action(act)
{
}
~ActionJanitor()
{
m_action(m_object);
}
private:
OBJECT &m_object;
ACTION &m_action;
};
// delete and zero the pointer
struct DeleteObject
{
template<class T>
void operator() (const T*& ptr) const
{
delete ptr;
ptr = 0;
}
};
};
//for stk name standard, DON'T use typedef, coz it's template base
#define CTJanitor
#define CTArrayJanitor stk::ArrayJanitor
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -