]> git.saurik.com Git - apple/javascriptcore.git/blob - wtf/OwnArrayPtr.h
JavaScriptCore-621.1.tar.gz
[apple/javascriptcore.git] / wtf / OwnArrayPtr.h
1 /*
2 * Copyright (C) 2006 Apple Computer, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public License
15 * along with this library; see the file COPYING.LIB. If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
18 *
19 */
20
21 #ifndef WTF_OwnArrayPtr_h
22 #define WTF_OwnArrayPtr_h
23
24 #include <algorithm>
25 #include <wtf/Assertions.h>
26 #include <wtf/Noncopyable.h>
27
28 namespace WTF {
29
30 template <typename T> class OwnArrayPtr : public Noncopyable {
31 public:
32 explicit OwnArrayPtr(T* ptr = 0) : m_ptr(ptr) { }
33 ~OwnArrayPtr() { safeDelete(); }
34
35 T* get() const { return m_ptr; }
36 T* release() { T* ptr = m_ptr; m_ptr = 0; return ptr; }
37
38 void set(T* ptr) { ASSERT(m_ptr != ptr); safeDelete(); m_ptr = ptr; }
39 void clear() { safeDelete(); m_ptr = 0; }
40
41 T& operator*() const { ASSERT(m_ptr); return *m_ptr; }
42 T* operator->() const { ASSERT(m_ptr); return m_ptr; }
43
44 T& operator[](std::ptrdiff_t i) const { ASSERT(m_ptr); ASSERT(i >= 0); return m_ptr[i]; }
45
46 bool operator!() const { return !m_ptr; }
47
48 // This conversion operator allows implicit conversion to bool but not to other integer types.
49 #if COMPILER(WINSCW)
50 operator bool() const { return m_ptr; }
51 #else
52 typedef T* OwnArrayPtr::*UnspecifiedBoolType;
53 operator UnspecifiedBoolType() const { return m_ptr ? &OwnArrayPtr::m_ptr : 0; }
54 #endif
55
56 void swap(OwnArrayPtr& o) { std::swap(m_ptr, o.m_ptr); }
57
58 private:
59 void safeDelete() { typedef char known[sizeof(T) ? 1 : -1]; if (sizeof(known)) delete [] m_ptr; }
60
61 T* m_ptr;
62 };
63
64 template <typename T> inline void swap(OwnArrayPtr<T>& a, OwnArrayPtr<T>& b) { a.swap(b); }
65
66 template <typename T> inline T* getPtr(const OwnArrayPtr<T>& p)
67 {
68 return p.get();
69 }
70
71 } // namespace WTF
72
73 using WTF::OwnArrayPtr;
74
75 #endif // WTF_OwnArrayPtr_h