2015-02-16 21:31:07 +01:00
|
|
|
#pragma once
|
2015-10-15 12:58:16 +02:00
|
|
|
#ifndef MESSMER_CPPUTILS_POINTER_OPTIONALOWNERSHIPPOINTER_H_
|
|
|
|
#define MESSMER_CPPUTILS_POINTER_OPTIONALOWNERSHIPPOINTER_H_
|
2015-02-16 21:31:07 +01:00
|
|
|
|
2015-07-21 15:18:14 +02:00
|
|
|
#include "unique_ref.h"
|
2015-06-10 17:17:41 +02:00
|
|
|
#include <functional>
|
2015-02-16 21:31:07 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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<typename T>
|
|
|
|
using optional_ownership_ptr = std::unique_ptr<T, std::function<void(T*)>>;
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
optional_ownership_ptr<T> WithOwnership(std::unique_ptr<T> obj) {
|
|
|
|
auto deleter = obj.get_deleter();
|
|
|
|
return optional_ownership_ptr<T>(obj.release(), [deleter](T* obj){deleter(obj);});
|
|
|
|
}
|
|
|
|
|
2015-07-21 15:18:14 +02:00
|
|
|
template <typename T>
|
|
|
|
optional_ownership_ptr<T> WithOwnership(unique_ref<T> obj) {
|
|
|
|
return WithOwnership(to_unique_ptr(std::move(obj)));
|
|
|
|
}
|
|
|
|
|
2015-02-16 21:31:07 +01:00
|
|
|
template<typename T>
|
|
|
|
optional_ownership_ptr<T> WithoutOwnership(T *obj) {
|
|
|
|
return optional_ownership_ptr<T>(obj, [](T*){});
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
optional_ownership_ptr<T> null() {
|
|
|
|
return WithoutOwnership<T>(nullptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif
|