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