WTF
OwnArrayPtr.h
Go to the documentation of this file.00001 // -*- mode: c++; c-basic-offset: 4 -*- 00002 /* 00003 * Copyright (C) 2006 Apple Computer, Inc. 00004 * 00005 * This library is free software; you can redistribute it and/or 00006 * modify it under the terms of the GNU Library General Public 00007 * License as published by the Free Software Foundation; either 00008 * version 2 of the License, or (at your option) any later version. 00009 * 00010 * This library is distributed in the hope that it will be useful, 00011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 00013 * Library General Public License for more details. 00014 * 00015 * You should have received a copy of the GNU Library General Public License 00016 * along with this library; see the file COPYING.LIB. If not, write to 00017 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 00018 * Boston, MA 02110-1301, USA. 00019 * 00020 */ 00021 00022 #ifndef WTF_OwnArrayPtr_h 00023 #define WTF_OwnArrayPtr_h 00024 00025 #include <algorithm> 00026 #include "Assertions.h" 00027 #include "Noncopyable.h" 00028 00029 namespace WTF { 00030 00031 template <typename T> class OwnArrayPtr : Noncopyable { 00032 public: 00033 explicit OwnArrayPtr(T* ptr = 0) : m_ptr(ptr) { } 00034 ~OwnArrayPtr() { safeDelete(); } 00035 00036 T* get() const { return m_ptr; } 00037 T* release() { T* ptr = m_ptr; m_ptr = 0; return ptr; } 00038 00039 void set(T* ptr) { ASSERT(m_ptr != ptr); safeDelete(); m_ptr = ptr; } 00040 void clear() { safeDelete(); m_ptr = 0; } 00041 00042 T& operator*() const { ASSERT(m_ptr); return *m_ptr; } 00043 T* operator->() const { ASSERT(m_ptr); return m_ptr; } 00044 00045 T& operator[](std::ptrdiff_t i) const { ASSERT(m_ptr); ASSERT(i >= 0); return m_ptr[i]; } 00046 00047 bool operator!() const { return !m_ptr; } 00048 00049 // This conversion operator allows implicit conversion to bool but not to other integer types. 00050 typedef T* (OwnArrayPtr::*UnspecifiedBoolType)() const; 00051 operator UnspecifiedBoolType() const { return m_ptr ? &OwnArrayPtr::get : 0; } 00052 00053 void swap(OwnArrayPtr& o) { std::swap(m_ptr, o.m_ptr); } 00054 00055 private: 00056 void safeDelete() { typedef char known[sizeof(T) ? 1 : -1]; if (sizeof(known)) delete [] m_ptr; } 00057 00058 T* m_ptr; 00059 }; 00060 00061 template <typename T> inline void swap(OwnArrayPtr<T>& a, OwnArrayPtr<T>& b) { a.swap(b); } 00062 00063 } // namespace WTF 00064 00065 using WTF::OwnArrayPtr; 00066 00067 #endif // WTF_OwnArrayPtr_h