| 1 |
/* |
| 2 |
* This file is a part of Luminance HDR package. |
| 3 |
* ---------------------------------------------------------------------- |
| 4 |
* Copyright (C) 2012 Davide Anastasia |
| 5 |
* |
| 6 |
* This program is free software; you can redistribute it and/or modify |
| 7 |
* it under the terms of the GNU General Public License as published by |
| 8 |
* the Free Software Foundation; either version 2 of the License, or |
| 9 |
* (at your option) any later version. |
| 10 |
* |
| 11 |
* This program is distributed in the hope that it will be useful, |
| 12 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
* GNU General Public License for more details. |
| 15 |
* |
| 16 |
* You should have received a copy of the GNU General Public License |
| 17 |
* along with this program; if not, write to the Free Software |
| 18 |
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 19 |
* ---------------------------------------------------------------------- |
| 20 |
*/ |
| 21 |
|
| 22 |
#ifndef RESOURCEHANDLER_H |
| 23 |
#define RESOURCEHANDLER_H |
| 24 |
|
| 25 |
namespace pfs { |
| 26 |
namespace utils { |
| 27 |
|
| 28 |
template <typename T> |
| 29 |
struct ResourceHandlerTraits { |
| 30 |
static inline void cleanup(T *p) { delete p; } |
| 31 |
}; |
| 32 |
|
| 33 |
//! \brief This class resemble QScopedPointer or std::scoped_ptr |
| 34 |
//! however, it doesn't provide and operator*(), which allow to store |
| 35 |
//! a pointer to void |
| 36 |
template <typename T, typename Traits = ResourceHandlerTraits<T>> |
| 37 |
class ResourceHandler { |
| 38 |
public: |
| 39 |
ResourceHandler(T *p = 0) : p_(p) {} |
| 40 |
|
| 41 |
inline void reset(T *p = 0) { |
| 42 |
if (p == p_) return; |
| 43 |
if (p_ != 0) { |
| 44 |
Traits::cleanup(p_); |
| 45 |
} |
| 46 |
p_ = p; |
| 47 |
} |
| 48 |
|
| 49 |
inline ~ResourceHandler() { |
| 50 |
T *oldD = this->p_; |
| 51 |
Traits::cleanup(oldD); |
| 52 |
this->p_ = 0; |
| 53 |
} |
| 54 |
|
| 55 |
inline T *data() { return p_; } |
| 56 |
|
| 57 |
inline const T *data() const { return p_; } |
| 58 |
|
| 59 |
inline T *take() { |
| 60 |
T *old_p = p_; |
| 61 |
p_ = 0; |
| 62 |
return old_p; |
| 63 |
} |
| 64 |
|
| 65 |
inline operator bool() const { return p_; } |
| 66 |
|
| 67 |
inline bool operator!() const { return !p_; } |
| 68 |
|
| 69 |
private: |
| 70 |
ResourceHandler(const ResourceHandler &); |
| 71 |
ResourceHandler &operator=(const ResourceHandler &); |
| 72 |
|
| 73 |
T *p_; |
| 74 |
}; |
| 75 |
|
| 76 |
} // utils |
| 77 |
} // pfs |
| 78 |
|
| 79 |
#endif // RESOURCEHANDLER_H |