generic_type ref-counting pointer class for C/C++ objects
/*!
Smart pointer to dynamically allocated objects.
This is template pointer-wrapping class that stores the associated reference counter along with the
object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard,
but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library).
Basically, you can use "Ptr<MyObjectType> ptr" (or faster "const Ptr<MyObjectType>& ptr" for read-only access)
everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class.
To make it all work, you need to specialize Ptr<>::delete_obj(), like:
\code
template<> void Ptr<MyObjectType>::delete_obj() { call_destructor_func(obj); }
\endcode
\note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(),
since the default implementation calls "delete obj;"}
\note{Another good property of the class is that the operations on the reference counter are atomic,
i.e. it is safe to use the class in multi-threaded applications}
*/
template<typename _Tp> class CV_EXPORTS Ptr
{
public:
//! empty constructor
Ptr();
//! take ownership of the pointer. The associated reference counter is allocated and set to 1
Ptr(_Tp* _obj);
//! calls release()
~Ptr();
//! copy constructor. Copies the members and calls addref()
Ptr(const Ptr& ptr);
template<typename _Tp2> Ptr(const Ptr<_Tp2>& ptr);
//! copy operator. Calls ptr.addref() and release() before copying the members
Ptr& operator = (const Ptr& ptr);
//! increments the reference counter
void addref();
//! decrements the reference counter. If it reaches 0, delete_obj() is called
void release();
//! deletes the object. Override if needed
void delete_obj();
//! returns true iff obj==NULL
bool empty() const;
//! cast pointer to another type
template<typename _Tp2> Ptr<_Tp2> ptr();
template<typename _Tp2> const Ptr<_Tp2> ptr() const;
//! helper operators making "Ptr<T> ptr" use very similar to "T* ptr".
_Tp* operator -> ();
const _Tp* operator -> () const;
operator _Tp* ();
operator const _Tp*() const;
_Tp* obj; //< the object pointer.
int* refcount; //< the associated reference counter
};
opencv 智能指针 Ptr
最新推荐文章于 2024-07-24 16:15:40 发布