C/C++ API Reference
Loading...
Searching...
No Matches
shared_ptr.h
1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#ifndef PW_ALLOCATOR_PUBLIC_PW_ALLOCATOR_SHARED_PTR_H_
17#define PW_ALLOCATOR_PUBLIC_PW_ALLOCATOR_SHARED_PTR_H_
18
19#include "pw_allocator/config.h"
20
21// TODO(b/402489948): Remove when portable atomics are provided by `pw_atomic`.
22#if PW_ALLOCATOR_HAS_ATOMICS
23
24#include <cstddef>
25#include <cstdint>
26#include <utility>
27
28#include "pw_allocator/allocator.h"
29#include "pw_allocator/deallocator.h"
30#include "pw_allocator/internal/control_block.h"
31#include "pw_allocator/internal/managed_ptr.h"
32#include "pw_allocator/layout.h"
33#include "pw_allocator/unique_ptr.h"
34#include "pw_multibuf/properties.h"
35
36namespace pw {
37
39
40// Forward declarations.
41template <typename T>
42class WeakPtr;
43
44template <multibuf::Property...>
45class BasicMultiBuf;
46
62template <typename T>
63class SharedPtr final : public ::pw::allocator::internal::ManagedPtr<T> {
64 private:
65 using Base = ::pw::allocator::internal::ManagedPtr<T>;
66 using ControlBlock = ::pw::allocator::internal::ControlBlock;
67
68 public:
69 using element_type = typename Base::element_type;
70 using weak_type = WeakPtr<T>;
71
73 ~SharedPtr() { reset(); }
74
79 constexpr SharedPtr() noexcept = default;
80
85 constexpr SharedPtr(std::nullptr_t) noexcept : SharedPtr() {}
86
88 constexpr SharedPtr(const SharedPtr& other) noexcept : SharedPtr() {
89 *this = other;
90 }
91
96 template <typename U,
97 typename = std::enable_if_t<std::is_assignable_v<T*&, U*>>>
98 constexpr SharedPtr(const SharedPtr<U>& other) noexcept : SharedPtr() {
99 *this = other;
100 }
101
107 template <typename U,
108 typename = std::enable_if_t<std::is_assignable_v<T*&, U*>>>
109 SharedPtr(SharedPtr<U>&& other) noexcept : SharedPtr() {
110 *this = std::move(other);
111 }
112
122 SharedPtr(UniquePtr<T>& owned) noexcept;
123
127 constexpr SharedPtr& operator=(const SharedPtr& other) noexcept {
128 operator= <T>(other);
129 return *this;
130 }
131
138 template <typename U,
139 typename = std::enable_if_t<std::is_assignable_v<T*&, U*>>>
140 constexpr SharedPtr& operator=(const SharedPtr<U>& other) noexcept;
141
148 template <typename U,
149 typename = std::enable_if_t<std::is_assignable_v<T*&, U*>>>
150 SharedPtr& operator=(SharedPtr<U>&& other) noexcept;
151
156 SharedPtr& operator=(std::nullptr_t) noexcept;
157
169 template <typename U,
170 typename = std::enable_if_t<std::is_assignable_v<T*&, U*>>>
171 constexpr explicit operator const SharedPtr<U>&() const {
172 return static_cast<const SharedPtr<U>&>(
173 static_cast<const allocator::internal::BaseManagedPtr&>(*this));
174 }
175
176 [[nodiscard]] friend constexpr bool operator==(const SharedPtr& lhs,
177 std::nullptr_t) {
178 return lhs.Equals(nullptr);
179 }
180 [[nodiscard]] friend constexpr bool operator==(std::nullptr_t,
181 const SharedPtr& rhs) {
182 return rhs.Equals(nullptr);
183 }
184 [[nodiscard]] friend constexpr bool operator==(const SharedPtr& lhs,
185 const SharedPtr& rhs) {
186 return lhs.Equals(rhs) && lhs.control_block_ == rhs.control_block_;
187 }
188
189 [[nodiscard]] friend constexpr bool operator!=(const SharedPtr& lhs,
190 std::nullptr_t) {
191 return !lhs.Equals(nullptr);
192 }
193 [[nodiscard]] friend constexpr bool operator!=(std::nullptr_t,
194 const SharedPtr& rhs) {
195 return !rhs.Equals(nullptr);
196 }
197 [[nodiscard]] friend constexpr bool operator!=(const SharedPtr& lhs,
198 const SharedPtr& rhs) {
199 return !(lhs == rhs);
200 }
201
205 size_t size() const {
206 static_assert(std::is_array_v<T>,
207 "size() cannot be called on non-array types");
208 return control_block_ == nullptr ? 0 : control_block_->size();
209 }
210
213 int32_t use_count() const {
214 return control_block_ == nullptr ? 0 : control_block_->num_shared();
215 }
216
222 void reset() noexcept;
223
225 void swap(SharedPtr& other) noexcept;
226
229 template <typename PtrType>
230 bool owner_before(const PtrType& other) const noexcept {
231 return control_block_ < other.control_block();
232 }
233
234 private:
235 using Layout = allocator::Layout;
236
237 static constexpr bool is_unbounded_array_v =
238 allocator::internal::is_unbounded_array_v<T>;
239
240 // Allow construction with to the implementation of `MakeShared`.
241 friend class Allocator;
242
243 // Allow SharedPtr<T> to access SharedPtr<U> and vice versa.
244 template <typename>
245 friend class SharedPtr;
246
247 // Allow WeakPtr<T> to promote to a SharedPtr<T>.
248 template <typename>
249 friend class WeakPtr;
250
251 // Allow MultiBufs to decompose SharedPtr<T>.
252 template <multibuf::Property...>
253 friend class BasicMultiBuf;
254
265 template <typename... Args>
266 static SharedPtr Create(Allocator* allocator, Args&&... args);
267
279 static SharedPtr Create(Allocator* allocator, size_t count, size_t alignment);
280
285 SharedPtr(element_type* value, ControlBlock* control_block)
286 : Base(value), control_block_(control_block) {}
287
288 ControlBlock* control_block() const { return control_block_; }
289
291 template <typename U,
292 typename = std::enable_if_t<std::is_assignable_v<T*&, U*>>>
293 void CopyFrom(const SharedPtr<U>& other);
294
297 void Release();
298
300 template <typename U>
301 constexpr void CheckArrayTypes();
302
303 ControlBlock* control_block_ = nullptr;
304};
305
307
308// Template method implementations.
309
310template <typename T>
312 if constexpr (std::is_array_v<T>) {
313 control_block_ =
314 ControlBlock::Create(owned.deallocator(), owned.get(), owned.size());
315 } else {
316 control_block_ = ControlBlock::Create(owned.deallocator(), owned.get(), 1);
317 }
318 if (control_block_ != nullptr) {
319 Base::CopyFrom(owned);
320 owned.Release();
321 }
322}
323
324template <typename T>
325template <typename... Args>
326SharedPtr<T> SharedPtr<T>::Create(Allocator* allocator, Args&&... args) {
327 static_assert(!std::is_array_v<T>);
328 auto* control_block = ControlBlock::Create(allocator, Layout::Of<T>(), 1);
329 if (control_block == nullptr) {
330 return nullptr;
331 }
332 auto* t = new (control_block->data()) T(std::forward<Args>(args)...);
333 return SharedPtr<T>(t, control_block);
334}
335
336template <typename T>
337SharedPtr<T> SharedPtr<T>::Create(Allocator* allocator,
338 size_t count,
339 size_t alignment) {
340 static_assert(allocator::internal::is_unbounded_array_v<T>);
341 Layout layout = Layout::Of<T>(count).Align(alignment);
342 auto* control_block = ControlBlock::Create(allocator, layout, count);
343 if (control_block == nullptr) {
344 return nullptr;
345 }
346 auto* t = new (control_block->data()) std::remove_extent_t<T>[count];
347 return SharedPtr<T>(t, control_block);
348}
349
350template <typename T>
351template <typename U, typename>
352constexpr SharedPtr<T>& SharedPtr<T>::operator=(
353 const SharedPtr<U>& other) noexcept {
354 CheckArrayTypes<U>();
355 CopyFrom(other);
356 if (control_block_ != nullptr) {
357 control_block_->IncrementShared();
358 }
359 return *this;
360}
361
362template <typename T>
363template <typename U, typename>
364SharedPtr<T>& SharedPtr<T>::operator=(SharedPtr<U>&& other) noexcept {
365 CheckArrayTypes<U>();
366 reset();
367 CopyFrom(other);
368 other.Release();
369 return *this;
370}
371
372template <typename T>
373SharedPtr<T>& SharedPtr<T>::operator=(std::nullptr_t) noexcept {
374 reset();
375 return *this;
376}
377
378template <typename T>
379void SharedPtr<T>::reset() noexcept {
380 if (*this == nullptr) {
381 return;
382 }
383 auto action = control_block_->DecrementShared();
384 if (action == ControlBlock::Action::kNone) {
385 // Other `SharedPtr`s associated with this control block remain.
386 Release();
387 return;
388 }
389
390 // This was the last `SharedPtr` associated with this control block.
391 Allocator* allocator = control_block_->allocator();
392 if (!Base::HasCapability(allocator, allocator::kSkipsDestroy)) {
393 if constexpr (std::is_array_v<T>) {
394 Base::Destroy(control_block_->size());
395 } else {
396 Base::Destroy();
397 }
398 }
399
400 if (action == ControlBlock::Action::kExpire) {
401 // Keep the control block. Trying to promote any of the remaining
402 // `WeakPtr`s will fail.
403 Base::Resize(allocator, control_block_, sizeof(ControlBlock));
404 } else {
405 // No `WeakPtr`s remain, and all of the memory can be freed.
406 Base::Deallocate(allocator, control_block_);
407 }
408
409 Release();
410}
411
412template <typename T>
413void SharedPtr<T>::swap(SharedPtr<T>& other) noexcept {
414 Base::Swap(other);
415 std::swap(control_block_, other.control_block_);
416}
417
418template <typename T>
419template <typename U, typename>
420void SharedPtr<T>::CopyFrom(const SharedPtr<U>& other) {
421 CheckArrayTypes<U>();
422 Base::CopyFrom(other);
423 control_block_ = other.control_block_;
424}
425
426template <typename T>
427void SharedPtr<T>::Release() {
428 Base::Release();
429 control_block_ = nullptr;
430}
431
432template <typename T>
433template <typename U>
434constexpr void SharedPtr<T>::CheckArrayTypes() {
435 if constexpr (std::is_array_v<T>) {
436 static_assert(std::is_array_v<U>,
437 "non-array type used with SharedPtr<T[]>");
438 } else {
439 static_assert(!std::is_array_v<U>, "array type used with SharedPtr<T>");
440 }
441}
442
443} // namespace pw
444
445// TODO(b/402489948): Remove when portable atomics are provided by `pw_atomic`.
446#endif // PW_ALLOCATOR_HAS_ATOMICS
447
448#endif // PW_ALLOCATOR_PUBLIC_PW_ALLOCATOR_SHARED_PTR_H_
Definition: allocator.h:43
Definition: multibuf_v2.h:185
Definition: shared_ptr.h:63
size_t size() const
Definition: shared_ptr.h:205
void swap(SharedPtr &other) noexcept
Swaps the managed pointer and deallocator of this and another object.
Definition: shared_ptr.h:413
constexpr SharedPtr & operator=(const SharedPtr< U > &other) noexcept
SharedPtr & operator=(SharedPtr< U > &&other) noexcept
SharedPtr(SharedPtr< U > &&other) noexcept
Definition: shared_ptr.h:109
~SharedPtr()
Releases any currently-held value.
Definition: shared_ptr.h:73
constexpr SharedPtr() noexcept=default
constexpr SharedPtr(const SharedPtr &other) noexcept
Copy-constructs a SharedPtr<T> from a SharedPtr<T>.
Definition: shared_ptr.h:88
int32_t use_count() const
Definition: shared_ptr.h:213
constexpr SharedPtr(const SharedPtr< U > &other) noexcept
Definition: shared_ptr.h:98
constexpr SharedPtr & operator=(const SharedPtr &other) noexcept
Definition: shared_ptr.h:127
void reset() noexcept
Definition: shared_ptr.h:379
Definition: unique_ptr.h:43
Definition: weak_ptr.h:37
Definition: layout.h:58
Property
Basic properties of a MultiBuf.
Definition: properties.h:25
The Pigweed namespace.
Definition: alignment.h:27