/* * smartpointer.h * Android * * Copyright 2005 The Android Open Source Project * */ #ifndef ANDROID_SMART_POINTER_H #define ANDROID_SMART_POINTER_H #include #include #include // --------------------------------------------------------------------------- namespace android { // --------------------------------------------------------------------------- #define COMPARE(_op_) \ inline bool operator _op_ (const sp& o) const { \ return m_ptr _op_ o.m_ptr; \ } \ inline bool operator _op_ (const T* o) const { \ return m_ptr _op_ o; \ } \ template \ inline bool operator _op_ (const sp& o) const { \ return m_ptr _op_ o.m_ptr; \ } \ template \ inline bool operator _op_ (const U* o) const { \ return m_ptr _op_ o; \ } // --------------------------------------------------------------------------- template class sp { public: inline sp() : m_ptr(0) { } sp(T* other); sp(const sp& other); template sp(U* other); template sp(const sp& other); ~sp(); // Assignment sp& operator = (T* other); sp& operator = (const sp& other); template sp& operator = (const sp& other); template sp& operator = (U* other); // Reset void clear(); // Accessors inline T& operator* () const { return *m_ptr; } inline T* operator-> () const { return m_ptr; } inline T* get() const { return m_ptr; } // Operators COMPARE(==) COMPARE(!=) COMPARE(>) COMPARE(<) COMPARE(<=) COMPARE(>=) private: template friend class sp; T* m_ptr; }; // --------------------------------------------------------------------------- // No user serviceable parts below here. template sp::sp(T* other) : m_ptr(other) { if (other) other->incStrong(this); } template sp::sp(const sp& other) : m_ptr(other.m_ptr) { if (m_ptr) m_ptr->incStrong(this); } template template sp::sp(U* other) : m_ptr(other) { if (other) other->incStrong(this); } template template sp::sp(const sp& other) : m_ptr(other.m_ptr) { if (m_ptr) m_ptr->incStrong(this); } template sp::~sp() { if (m_ptr) m_ptr->decStrong(this); } template sp& sp::operator = (const sp& other) { if (other.m_ptr) other.m_ptr->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other.m_ptr; return *this; } template sp& sp::operator = (T* other) { if (other) other->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other; return *this; } template template sp& sp::operator = (const sp& other) { if (other.m_ptr) other.m_ptr->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other.m_ptr; return *this; } template template sp& sp::operator = (U* other) { if (other) other->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other; return *this; } template void sp::clear() { if (m_ptr) { m_ptr->decStrong(this); m_ptr = 0; } } // --------------------------------------------------------------------------- }; // namespace android // --------------------------------------------------------------------------- #endif // ANDROID_SMART_POINTER_H