File indexing completed on 2024-05-12 15:43:39

0001 /*
0002  *  Copyright (C) 2006 Apple Computer, Inc.
0003  *
0004  *  This library is free software; you can redistribute it and/or
0005  *  modify it under the terms of the GNU Library General Public
0006  *  License as published by the Free Software Foundation; either
0007  *  version 2 of the License, or (at your option) any later version.
0008  *
0009  *  This library is distributed in the hope that it will be useful,
0010  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
0011  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0012  *  Library General Public License for more details.
0013  *
0014  *  You should have received a copy of the GNU Library General Public License
0015  *  along with this library; see the file COPYING.LIB.  If not, write to
0016  *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
0017  *  Boston, MA 02110-1301, USA.
0018  *
0019  */
0020 
0021 #ifndef WTF_OwnPtr_h
0022 #define WTF_OwnPtr_h
0023 
0024 #include <algorithm>
0025 #include <wtf/Assertions.h>
0026 #include <wtf/Noncopyable.h>
0027 
0028 namespace WTF
0029 {
0030 
0031 template <typename T> class OwnPtr : Noncopyable
0032 {
0033 public:
0034     explicit OwnPtr(T *ptr = nullptr) : m_ptr(ptr) { }
0035     ~OwnPtr()
0036     {
0037         safeDelete();
0038     }
0039 
0040     T *get() const
0041     {
0042         return m_ptr;
0043     }
0044     T *release()
0045     {
0046         T *ptr = m_ptr;
0047         m_ptr = nullptr;
0048         return ptr;
0049     }
0050 
0051     void set(T *ptr)
0052     {
0053         ASSERT(m_ptr != ptr);
0054         safeDelete();
0055         m_ptr = ptr;
0056     }
0057     void clear()
0058     {
0059         safeDelete();
0060         m_ptr = nullptr;
0061     }
0062 
0063     T &operator*() const
0064     {
0065         ASSERT(m_ptr);
0066         return *m_ptr;
0067     }
0068     T *operator->() const
0069     {
0070         ASSERT(m_ptr);
0071         return m_ptr;
0072     }
0073 
0074     bool operator!() const
0075     {
0076         return !m_ptr;
0077     }
0078 
0079     // This conversion operator allows implicit conversion to bool but not to other integer types.
0080     typedef T *(OwnPtr::*UnspecifiedBoolType)() const;
0081     operator UnspecifiedBoolType() const
0082     {
0083         return m_ptr ? &OwnPtr::get : nullptr;
0084     }
0085 
0086     void swap(OwnPtr &o)
0087     {
0088         std::swap(m_ptr, o.m_ptr);
0089     }
0090 
0091 private:
0092     void safeDelete()
0093     {
0094         typedef char known[sizeof(T) ? 1 : -1];
0095         if (sizeof(known)) {
0096             delete m_ptr;
0097         }
0098     }
0099 
0100     T *m_ptr;
0101 };
0102 
0103 template <typename T> inline void swap(OwnPtr<T> &a, OwnPtr<T> &b)
0104 {
0105     a.swap(b);
0106 }
0107 
0108 } // namespace WTF
0109 
0110 using WTF::OwnPtr;
0111 
0112 #endif // WTF_OwnPtr_h