1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
| #ifndef SMART_POINTER_HPP
#define SMART_POINTER_HPP
#include <cassert>
/**
* @brief ONLY USED IN SmartPointer
**/
template<typename T, typename PtrType = T>
class SharedReference
{
public:
SharedReference(PtrType* ptr):
_Ptr(nullptr),
_Count(1)
{
_Ptr = ptr;
}
/**
* @brief The destructor.
*
* Bye default, use operator delete.
* To override this behavior, free _Ptr and reset it to NULL in the derived destructor.
**/
~SharedReference()
{
assert(_Count == 0);
if(_Ptr)
{
delete _Ptr, _Ptr = nullptr;
}
}
public:
bool releaseOne()
{
_Count--;
if(_Count == 0) {
return true;
}
else {
return false;
}
}
void increaseOne()
{
_Count++;
}
PtrType* data() {
return _Ptr;
}
const PtrType* c_data() {
return _Ptr;
}
protected:
PtrType* _Ptr;
private:
int _Count;
};
/**
* @brief Smart pointer.
*
* The data is auto-freed after the destruction of this object.
**/
template<typename T>
class SmartPointer
{
public:
typedef T value_type;
public:
/**
* @brief The constructor.
*
* @param[in] obj The object to be managed.
**/
explicit SmartPointer(value_type *ptr = nullptr);
/**
* @brief The copy constructor.
*
* The object is not copied.
**/
SmartPointer(const SmartPointer&);
SmartPointer& operator=(const SmartPointer&);
SmartPointer& operator=(value_type*);
/**
* @brief The destructor.
*
* Release this count.
**/
~SmartPointer();
/**
* @brief Release this count to the current reference.
*
* If there are no count any more, the reference is freed.
**/
void release();
/**
* @brief Get if the object is not NULL.
**/
explicit operator bool() const;
/**
* @brief Get a pointer to the object.
*
* Require that the object is not NULL.
**/
value_type& operator*() { return *ptr();}
value_type* operator->() { return ptr();}
const value_type& operator*() const { return *c_ptr();}
const value_type* operator->() const { return c_ptr();}
/**
* @brief Get the data.
*
* The data must not be deleted.
* Require that the object is not NULL.
**/
value_type* ptr();
const value_type* c_ptr() const;
private:
SharedReference<T> *_Ref;
/**
* @brief Add one count to the reference.
*
* @return - The incremented Reference_t
* - Or NULL if there are no reference.
**/
SharedReference<T>* increase() const;
};
#include "SmartPointer.tpp"
#endif // SMART_POINTER_HPP |
Partager