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_OwnArrayPtr_h 0022 #define WTF_OwnArrayPtr_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 OwnArrayPtr : Noncopyable 0032 { 0033 public: 0034 explicit OwnArrayPtr(T *ptr = nullptr) : m_ptr(ptr) { } 0035 ~OwnArrayPtr() 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 T &operator[](std::ptrdiff_t i) const 0075 { 0076 ASSERT(m_ptr); 0077 ASSERT(i >= 0); 0078 return m_ptr[i]; 0079 } 0080 0081 bool operator!() const 0082 { 0083 return !m_ptr; 0084 } 0085 0086 // This conversion operator allows implicit conversion to bool but not to other integer types. 0087 typedef T *(OwnArrayPtr::*UnspecifiedBoolType)() const; 0088 operator UnspecifiedBoolType() const 0089 { 0090 return m_ptr ? &OwnArrayPtr::get : nullptr; 0091 } 0092 0093 void swap(OwnArrayPtr &o) 0094 { 0095 std::swap(m_ptr, o.m_ptr); 0096 } 0097 0098 private: 0099 void safeDelete() 0100 { 0101 typedef char known[sizeof(T) ? 1 : -1]; 0102 if (sizeof(known)) { 0103 delete [] m_ptr; 0104 } 0105 } 0106 0107 T *m_ptr; 0108 }; 0109 0110 template <typename T> inline void swap(OwnArrayPtr<T> &a, OwnArrayPtr<T> &b) 0111 { 0112 a.swap(b); 0113 } 0114 0115 } // namespace WTF 0116 0117 using WTF::OwnArrayPtr; 0118 0119 #endif // WTF_OwnArrayPtr_h