#pragma once #ifndef MESSMER_CPPUTILS_POINTER_OPTIONALOWNERSHIPPOINTER_H_ #define MESSMER_CPPUTILS_POINTER_OPTIONALOWNERSHIPPOINTER_H_ #include "unique_ref.h" #include /** * optional_ownership_ptr can be used to hold a pointer to an instance of an object. * The pointer might or might not have ownership of the object. * * If it has ownership, it will delete the stored object in its destructor. * If it doesn't have ownership, it won't. * * You can create such pointers with * - WithOwnership(ptr) * - WithoutOwnership(ptr) * - null() */ namespace cpputils { template using optional_ownership_ptr = std::unique_ptr>; template optional_ownership_ptr WithOwnership(std::unique_ptr obj) { auto deleter = obj.get_deleter(); return optional_ownership_ptr(obj.release(), [deleter](T* obj){deleter(obj);}); } template optional_ownership_ptr WithOwnership(unique_ref obj) { return WithOwnership(to_unique_ptr(std::move(obj))); } template optional_ownership_ptr WithoutOwnership(T *obj) { return optional_ownership_ptr(obj, [](T*){}); } template optional_ownership_ptr null() { return WithoutOwnership(nullptr); } } #endif