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
|
#ifndef __BTAS_UTIL_OPTIONAL_PTR_H
#define __BTAS_UTIL_OPTIONAL_PTR_H 1
#include <memory>
namespace btas {
/**
optional_ptr<T> functions either as a raw unmanaged pointer
or as a smart pointer of type managed_ptr depending on whether
it is initialized through the set_external method or
the set_managed method
*/
template <typename T, typename managed_ptr = std::unique_ptr<T>>
class optional_ptr
{
public:
using ptr = T*;
optional_ptr() : p_(nullptr) { }
optional_ptr(optional_ptr&& other)
:
p_(other.p_),
up_(std::move(other.up_))
{ }
T&
operator*() const { return *p_; }
ptr
operator->() const { return p_; }
void
set_managed(ptr new_p)
{
up_ = std::move(managed_ptr(new_p));
p_ = up_.get();
}
void
set_external(ptr ext_p)
{
p_ = ext_p;
up_.reset();
}
private:
ptr p_;
managed_ptr up_;
};
} // namespace btas
#endif // __BTAS_UTIL_OPTIONAL_PTR_H
|