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
|
/**
* stack_ptr.h
*
* Implementation of an object that behaves like a
* smart pointer but is actually managed on the stack
*
* @copyright 2016 Copernica B.V.
*/
/**
* Dependencies
*/
#include <type_traits>
#include <utility>
/**
* Set up namespace
*/
namespace AMQP {
/**
* Stack-based smart pointer
*/
template <typename T>
class stack_ptr
{
private:
/**
* Storage for the object
* @var typename std::aligned_storage<sizeof(T), alignof(T)>::type
*/
typename std::aligned_storage<sizeof(T), alignof(T)>::type _data;
/**
* Is the pointer initialized?
* @var boolean
*/
bool _initialized = false;
public:
/**
* Constructor
*/
stack_ptr() = default;
/**
* Copy and moving is disabled
*
* @param that The stack_ptr we refuse to copy/move
*/
stack_ptr(const stack_ptr &that) = delete;
stack_ptr(stack_ptr &&that) = delete;
/**
* Destructor
*/
~stack_ptr()
{
// reset the pointer
reset();
}
/**
* Reset the pointer
*/
void reset()
{
// are we initialized?
if (!_initialized) return;
// destroy the object
reinterpret_cast<T*>(&_data)->~T();
// the object is not currently initialized
_initialized = false;
}
/**
* Construct the object
*
* @param ... Zero or more constructor arguments for T
*/
template <typename... Arguments>
void construct(Arguments&&... parameters)
{
// first reset the current object
reset();
// initialize new object
new (&_data) T(std::forward<Arguments>(parameters)...);
// we are now initialized
_initialized = true;
}
/**
* Is the object initialized?
*
* @return Are we currently managing an object?
*/
operator bool() const
{
// are we initialized with an object?
return _initialized;
}
/**
* Retrieve a pointer to the object
*
* @return Pointer to the object or nullptr if no object is managed
*/
T *get() const
{
// do we have a managed object
if (!_initialized) return nullptr;
// return pointer to the managed object
return const_cast<T*>(reinterpret_cast<const T*>(&_data));
}
/**
* Retrieve a reference to the object
*
* @return Reference to the object, undefined if no object is managed
*/
T &operator*() const
{
// dereference the pointer
return *operator->();
}
/**
* Retrieve a pointer to the object
*
* @return Pointer to the object, undefined if no object is managed
*/
T *operator->() const
{
// return pointer to the managed object
return const_cast<T*>(reinterpret_cast<const T*>(&_data));
}
};
/**
* End namespace
*/
}
|