Debian Codegraph @

src/atlas/util/ObjectHandle.h

raw
1 /*
2 * (C) Copyright 2013 ECMWF.
3 *
4 * This software is licensed under the terms of the Apache Licence Version 2.0
5 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
6 * In applying this licence, ECMWF does not waive the privileges and immunities
7 * granted to it by virtue of its status as an intergovernmental organisation
8 * nor does it submit to any jurisdiction.
9 */
10
11 #pragma once
12
13 #include "atlas/library/config.h"
14
15 namespace atlas {
16 namespace util {
17
18 class Object;
19
20 class ObjectHandleBase {
21 public:
22 ObjectHandleBase() = default;
23 ObjectHandleBase(const Object* object): object_(const_cast<Object*>(object)) { attach(); }
24
25 virtual ~ObjectHandleBase() {
26 if (object_) {
27 release();
28 }
29 }
30
31 const ObjectHandleBase& operator=(const ObjectHandleBase& other) {
32 if (object_ != other.object_) {
33 assign(other);
34 }
35 return *this;
36 }
37
38 operator bool() const { return object_ != nullptr; }
39
40 void reset(const Object* other) {
41 if (object_ != other) {
42 assign(other);
43 }
44 }
45
46 int owners() const;
47
48 private:
49 void release();
50
51 void assign(const ObjectHandleBase& other);
52
53 void assign(const Object* other);
54
55 void attach();
56
57 bool null() const { return (object_ == nullptr); }
58
59 protected:
60 Object* object_{nullptr};
61 };
62
63 template <typename T>
64 class ObjectHandle : public ObjectHandleBase {
65 public:
66 using Implementation = T;
67 using Handle = ObjectHandle<T>;
68
69 public:
70 ObjectHandle() = default;
71 ObjectHandle(const T* object): ObjectHandleBase(reinterpret_cast<const Object*>(object)) {}
72 ObjectHandle(const ObjectHandle& handle): ObjectHandleBase(reinterpret_cast<const Object*>(handle.get())) {}
73 ObjectHandle& operator=(const ObjectHandle& handle) {
74 reset(handle.get());
75 return *this;
76 }
77 ATLAS_ALWAYS_INLINE T* get() { return reinterpret_cast<T*>(object_); }
78 ATLAS_ALWAYS_INLINE const T* get() const { return reinterpret_cast<const T*>(object_); }
79 ATLAS_ALWAYS_INLINE const T* operator->() const { return get(); }
80 ATLAS_ALWAYS_INLINE T* operator->() { return get(); }
81 ATLAS_ALWAYS_INLINE const T& operator*() const { return *get(); }
82 ATLAS_ALWAYS_INLINE T& operator*() { return *get(); }
83 ATLAS_ALWAYS_INLINE void reset(const T* object) {
84 ObjectHandleBase::reset(reinterpret_cast<const Object*>(object));
85 }
86 };
87
88 } // namespace util
89 } // namespace atlas