forked from cryfs/cryfs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptional_ownership_ptr.h
More file actions
49 lines (39 loc) · 1.24 KB
/
Copy pathoptional_ownership_ptr.h
File metadata and controls
49 lines (39 loc) · 1.24 KB
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
#pragma once
#ifndef MESSMER_CPPUTILS_POINTER_OPTIONALOWNERSHIPPOINTER_H_
#define MESSMER_CPPUTILS_POINTER_OPTIONALOWNERSHIPPOINTER_H_
#include "unique_ref.h"
#include <functional>
/**
* 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);
}
template <typename T>
optional_ownership_ptr<T> WithOwnership(unique_ref<T> obj) {
return WithOwnership(static_cast<std::unique_ptr<T>>(std::move(obj)));
}
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