| 1 | /* |
| 2 | * Copyright (C) 2005 Dizzy |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or |
| 5 | * modify it under the terms of the GNU General Public License |
| 6 | * as published by the Free Software Foundation; either version 2 |
| 7 | * of the License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program 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 |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 17 | */ |
| 18 | |
| 19 | #ifndef PVPGN_SCOPED_ARRAY_H |
| 20 | #define PVPGN_SCOPED_ARRAY_H |
| 21 | |
| 22 | namespace pvpgn |
| 23 | { |
| 24 | |
| 25 | template<typename T> |
| 26 | class scoped_array |
| 27 | { |
| 28 | public: |
| 29 | /** initilize the object aquiring ownership of the given parameter (0 for no onwership) */ |
| 30 | explicit scoped_array(T* ptr_ = 0) |
| 31 | :ptr(ptr_) {} |
| 32 | |
| 33 | /** initilize the object from a blind pointer supporting implicit conversions */ |
| 34 | template<typename V> |
| 35 | explicit scoped_array(V* ptr_) |
| 36 | :ptr(ptr_) {} |
| 37 | |
| 38 | /** release memory if aquired ownershipt */ |
| 39 | ~scoped_array() throw() { |
| 40 | cleanup(); |
| 41 | } |
| 42 | |
| 43 | /** get the wrapped array pointer */ |
| 44 | T* get() const { return ptr; } |
| 45 | |
| 46 | /** release ownership of the array */ |
| 47 | T* release() { |
| 48 | T* tmp = ptr; |
| 49 | ptr = 0; |
| 50 | return tmp; |
| 51 | } |
| 52 | |
| 53 | /** reinitilize object, release owned resource first if any */ |
| 54 | void reset(T* ptr_ = 0) { |
| 55 | cleanup(); |
| 56 | ptr = ptr_; |
| 57 | } |
| 58 | |
| 59 | /** reinitilize object, supports implicit conversions */ |
| 60 | template<typename V> |
| 61 | void reset(V* ptr_) { |
| 62 | cleanup(); |
| 63 | ptr = ptr_; |
| 64 | } |
| 65 | |
| 66 | /** allow indexed const dereferencing access to the wrapped array */ |
| 67 | const T& operator[](unsigned idx) const { |
| 68 | return ptr[idx]; |
| 69 | } |
| 70 | |
| 71 | /** allow indexed dereferencing access to the wrapped array */ |
| 72 | T& operator[](unsigned idx) { |
| 73 | return ptr[idx]; |
| 74 | } |
| 75 | |
| 76 | private: |
| 77 | T* ptr; |
| 78 | |
| 79 | /* do not allow to copy a scoped_array */ |
| 80 | scoped_array(const scoped_array&); |
| 81 | scoped_array& operator=(const scoped_array&); |
| 82 | |
| 83 | void cleanup() { |
| 84 | if (ptr) delete[] ptr; |
| 85 | } |
| 86 | }; |
| 87 | |
| 88 | } |
| 89 | |
| 90 | #endif |