92 lines
1.9 KiB
C++
92 lines
1.9 KiB
C++
#ifndef SMARTHANDLE_H
|
|
#define SMARTHANDLE_H
|
|
|
|
/**
|
|
* Smart handle is like a smart pointer. It simply deletes the object on destruction using a custom deleter
|
|
* It differs from `std::unique_ptr` by that it doesn't expect a pointer
|
|
*/
|
|
template <typename T, typename Deleter>
|
|
class SmartHandle
|
|
{
|
|
public:
|
|
typedef T value_type;
|
|
typedef Deleter deleter_function;
|
|
private:
|
|
T _value;
|
|
Deleter _deleter;
|
|
bool _doDelete;
|
|
void _delete();
|
|
public:
|
|
SmartHandle();
|
|
SmartHandle(T value, Deleter deleter);
|
|
SmartHandle(const SmartHandle& orig) = delete;
|
|
SmartHandle& operator=(const SmartHandle& orig) = delete;
|
|
SmartHandle(SmartHandle&& src);
|
|
~SmartHandle();
|
|
T get() const;
|
|
void reset();
|
|
void reset(T value, Deleter deleter);
|
|
};
|
|
|
|
template <typename T, typename Deleter>
|
|
SmartHandle<T,Deleter>::SmartHandle()
|
|
{
|
|
this->_doDelete = 0;
|
|
}
|
|
|
|
template <typename T, typename Deleter>
|
|
SmartHandle<T,Deleter>::SmartHandle(T value, Deleter deleter)
|
|
{
|
|
this->_doDelete = 0;
|
|
this->reset(value,deleter);
|
|
}
|
|
|
|
template<typename T, typename Deleter>
|
|
SmartHandle<T,Deleter>::SmartHandle(SmartHandle&& src)
|
|
{
|
|
this->reset(src._value,src._deleter);
|
|
src._doDelete = 0;
|
|
}
|
|
|
|
template <typename T, typename Deleter>
|
|
void SmartHandle<T,Deleter>::reset(T value, Deleter deleter)
|
|
{
|
|
if(this->_doDelete) {
|
|
this->_delete();
|
|
}
|
|
this->_value = value;
|
|
this->_deleter = deleter;
|
|
this->_doDelete = 1;
|
|
}
|
|
|
|
template <typename T, typename Deleter>
|
|
void SmartHandle<T,Deleter>::reset()
|
|
{
|
|
if(this->_doDelete) {
|
|
this->_delete();
|
|
}
|
|
}
|
|
|
|
template <typename T, typename Deleter>
|
|
T SmartHandle<T,Deleter>::get() const
|
|
{
|
|
return _value;
|
|
}
|
|
|
|
template <typename T, typename Deleter>
|
|
void SmartHandle<T,Deleter>::_delete()
|
|
{
|
|
_deleter(_value);
|
|
this->_doDelete = 0;
|
|
}
|
|
|
|
template <typename T, typename Deleter>
|
|
SmartHandle<T,Deleter>::~SmartHandle()
|
|
{
|
|
if(this->_doDelete) {
|
|
_delete();
|
|
}
|
|
}
|
|
|
|
#endif // SMARTHANDLE_H
|