forked from CleverRaven/Cataclysm-DDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
safe_reference.h
75 lines (58 loc) · 1.99 KB
/
safe_reference.h
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
#pragma once
#ifndef CATA_SRC_SAFE_REFERENCE_H
#define CATA_SRC_SAFE_REFERENCE_H
/**
A pair of classes to provide safe references to objects.
A safe_reference_anchor is made a member of some object, and a safe_reference
to that object (or any other object with the same lifetime) can be obtained
from the safe_reference_anchor.
When the safe_reference is destroyed or assigned-to, all safe_references
derived from it are invalidated. When one attempts to fetch the referenced
object from an invalidated safe_reference, it returns nullptr.
The motivating use case is to store references to items in item_locations in a
way that is safe if that item is moved or destroyed.
*/
#include <memory>
template<typename T>
class safe_reference
{
public:
safe_reference() = default;
T *get() const {
return impl.lock().get();
}
explicit operator bool() const {
return !!*this;
}
bool operator!() const {
return impl.expired();
}
T &operator*() const {
return *get();
}
T *operator->() const {
return get();
}
private:
friend class safe_reference_anchor;
explicit safe_reference( const std::shared_ptr<T> &p ) : impl( p ) {}
std::weak_ptr<T> impl;
};
class safe_reference_anchor
{
public:
safe_reference_anchor();
safe_reference_anchor( const safe_reference_anchor & );
safe_reference_anchor( safe_reference_anchor && ) noexcept;
safe_reference_anchor &operator=( const safe_reference_anchor & );
safe_reference_anchor &operator=( safe_reference_anchor && ) noexcept;
template<typename T>
safe_reference<T> reference_to( T *object ) {
// Using the shared_ptr aliasing constructor
return safe_reference<T>( std::shared_ptr<T>( impl, object ) );
}
private:
struct empty {};
std::shared_ptr<empty> impl;
};
#endif // CATA_SRC_SAFE_REFERENCE_H