1.10
cow.h
1/*
2 * Copyright (C) 2018 Microchip Technology Inc. All rights reserved.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6#ifndef EGT_DETAIL_COW_H
7#define EGT_DETAIL_COW_H
8
9#include <egt/detail/meta.h>
10#include <memory>
11
17namespace egt
18{
19inline namespace v1
20{
21namespace detail
22{
23
31template <class T>
33{
34public:
35
37
39 explicit CopyOnWriteAllocate(T* t)
40 : m_ptr(t)
41 {}
42
44 explicit CopyOnWriteAllocate(const std::shared_ptr<T>& refptr)
45 : m_ptr(refptr)
46 {}
47
49 explicit operator bool() const
50 {
51 return !!m_ptr;
52 }
53
55 const T& operator*() const
56 {
57 allocate();
58 return *m_ptr;
59 }
60
63 {
64 detach();
65 return *m_ptr;
66 }
67
69 const T* operator->() const
70 {
71 allocate();
72 return m_ptr.operator->();
73 }
74
77 {
78 detach();
79 return m_ptr.operator->();
80 }
81
82private:
83
84 void allocate()
85 {
86 if (!m_ptr)
87 m_ptr = std::make_shared<T>();
88 }
89
90 void detach()
91 {
92 if (!m_ptr)
93 allocate();
94 else if (m_ptr && !m_ptr.unique())
95 m_ptr = std::make_shared<T>(*m_ptr);
96 }
97
98 std::shared_ptr<T> m_ptr;
99};
100
101}
102}
103}
104
105#endif
Copy-On-Write wrapper for an object or container.
Definition cow.h:33
CopyOnWriteAllocate(const std::shared_ptr< T > &refptr)
Construct with a shared_ptr to the object.
Definition cow.h:44
const T & operator*() const
Dereference operator. This will allocate.
Definition cow.h:55
T & operator*()
Dereference operator.
Definition cow.h:62
T * operator->()
Arrow operator.
Definition cow.h:76
const T * operator->() const
Arrow operator.
Definition cow.h:69
CopyOnWriteAllocate(T *t)
Construct with a pointer to the object. This now owns the pointer.
Definition cow.h:39
EGT framework namespace.
Definition animation.h:24