-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstrong_ptr.cppm
More file actions
2159 lines (1977 loc) · 60.3 KB
/
Copy pathstrong_ptr.cppm
File metadata and controls
2159 lines (1977 loc) · 60.3 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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024 - 2025 Khalil Estell and the libhal contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
module;
#include <cstddef>
#include <cstdint>
#include <array>
#include <exception>
#include <memory>
#include <memory_resource>
#include <system_error>
#include <type_traits>
#include <utility>
export module strong_ptr;
namespace mem::inline v1 {
// Forward declarations
export template<typename T>
class strong_ptr;
export template<typename T>
class weak_ptr;
export template<typename T>
class optional_ptr;
/**
* @brief Base class for monotonic allocators providing the pmr memory resource
* interface
*
* Implements std::pmr::memory_resource with monotonic (bump) allocation.
* Allocations advance a pointer forward through a buffer. Deallocations only
* decrement an allocation counter; memory is not reused. If the allocator is
* destroyed while memory is still allocated, std::terminate is called to
* prevent dangling references.
*
* @throws std::bad_alloc when insufficient space remains for an allocation
*/
struct monotonic_allocator_base : public std::pmr::memory_resource
{
/// @brief Destructor that calls std::terminate if allocated bytes is not zero
~monotonic_allocator_base() override
{
if (m_allocated_bytes != 0) {
std::terminate();
}
}
/// @brief Allocates memory by advancing a pointer through the buffer
/// @param p_bytes number of bytes to allocate
/// @param p_alignment required alignment for the allocation
/// @return pointer to the allocated memory
/// @throws std::bad_alloc if insufficient space remains
void* do_allocate(std::size_t p_bytes, std::size_t p_alignment) override
{
void* result = std::align(p_alignment, p_bytes, m_ptr, m_space);
if (result == nullptr) [[unlikely]] {
throw std::bad_alloc();
}
m_allocated_bytes += static_cast<decltype(m_allocated_bytes)>(p_bytes);
m_ptr = static_cast<std::uint8_t*>(result) + p_bytes;
m_space -= p_bytes;
return result;
};
/// @brief Records a deallocation by decrementing the allocation counter
/// @param p_bytes number of bytes being deallocated
void do_deallocate(void*, std::size_t p_bytes, std::size_t) override
{
m_allocated_bytes -= static_cast<decltype(m_allocated_bytes)>(p_bytes);
}
/// @brief Checks if two memory resources are the same object
[[nodiscard]] bool do_is_equal(
std::pmr::memory_resource const& p_other) const noexcept override
{
return *this == p_other;
}
/// @brief Remaining space in the buffer
size_t m_space = 0;
/// @brief Current position in the buffer
void* m_ptr = nullptr;
/// @brief Tracks total allocated bytes for leak detection
std::int32_t m_allocated_bytes = 0;
};
/**
* @brief A stack-allocated monotonic memory arena for use with pmr allocators
*
* Provides a fixed-size, stack-allocated buffer that serves as a
* std::pmr::memory_resource. Allocations advance sequentially through the
* buffer. Deallocations only track the byte count — memory is never reused.
* If the allocator is destroyed while allocations are still outstanding,
* std::terminate is called.
*
* Supports implicit conversion to std::pmr::memory_resource* and
* std::pmr::polymorphic_allocator<T>, and provides operator-> for direct
* allocate/deallocate calls.
*
* @tparam MemorySize number of bytes in the internal storage buffer
*/
export template<size_t MemorySize>
struct monotonic_allocator
{
/// @brief Initializes the internal buffer and sets up the base allocator
monotonic_allocator()
{
m_base.m_ptr = m_storage.data();
m_base.m_space = MemorySize;
}
/// @brief Returns a pointer to the underlying memory resource
std::pmr::memory_resource* resource()
{
return &m_base;
}
/// @brief Implicit conversion to std::pmr::memory_resource*
operator std::pmr::memory_resource*()
{
return &m_base;
}
/// @brief Arrow operator for direct access to memory resource methods
std::pmr::memory_resource* operator->()
{
return &m_base;
}
/// @brief Dereference operator returning the memory resource
std::pmr::memory_resource& operator*()
{
return m_base;
}
/// @brief Implicit conversion to std::pmr::polymorphic_allocator<T>
template<typename T>
operator std::pmr::polymorphic_allocator<T>()
{
return &m_base;
}
/// @brief The base allocator implementing the pmr interface
monotonic_allocator_base m_base{};
/// @brief Fixed-size storage buffer for allocations
std::array<std::byte, MemorySize> m_storage = {};
};
/**
* @brief Creates monotonic allocators with embedded memory pool & memory
* safety checks
*
* Allocated memory is fetched from the internal storage defined by the
* template parameter `StorageSizeBytes`.
*
* Allocations are monotonic, meaning sequential and always progressing
* forward. The amount of memory allocated is recorded. Previously allocated
* memory addresses are never returned from this memory resource. If the
* required space is not available `std::bad_alloc` is thrown.
*
* Every deallocation subtracts from the counter that records the total amount
* of memory allocated. When this allocator is destroyed, if the allocated
* amount of bytes is not 0, std::terminate is called. This is to ensure that
* references to memory within this buffer cannot become invalid.
*
* @tparam StorageSizeBytes - Number of bytes for allocator memory
* @return monotonic_allocator - the monotonic allocator arena
*/
export template<size_t StorageSizeBytes>
monotonic_allocator<StorageSizeBytes> make_monotonic_allocator()
{
return monotonic_allocator<StorageSizeBytes>();
}
/**
* @brief Control block for reference counting - type erased.
*
* This structure manages the lifetime of reference-counted objects by tracking
* strong and weak references. It also stores the memory allocator and destroy
* function used to clean up the object when no more references exist.
*/
struct ref_info
{
/**
* @brief Destroy function for ref counted object
*
* Always returns the total size of the object wrapped in a ref count object.
* Thus the size should normally be greater than sizeof(T). Expect sizeof(T) +
* sizeof(ref_info) and anything else the ref count object may contain.
*
* If a nullptr is passed to the destroy function, it returns the object size
* but does not destroy the object.
*/
using type_erased_destruct_function_t = std::size_t(void const*);
/// Initialize to 1 since creation implies a reference
std::pmr::memory_resource* allocator;
type_erased_destruct_function_t* destroy = nullptr;
int strong_count = 0;
int weak_count = 0;
// Add explicit constructor to avoid aggregate initialization issues
constexpr ref_info(std::pmr::memory_resource* p_allocator,
type_erased_destruct_function_t* p_destroy)
: allocator(p_allocator)
, destroy(p_destroy)
{
}
/**
* @brief Add strong reference to control block
*
*/
constexpr void add_ref()
{
strong_count++;
}
/**
* @brief Release strong reference from control block
*
* If this was the last strong reference, the pointed-to object will be
* destroyed. If there are no remaining weak references, the memory
* will also be deallocated.
*/
constexpr void release()
{
// Note: fetch_sub returns the previous value, if it was 1 and we subtracted
// 1, then the final value is 0. We check below 1 just in case another
// thread performs a fetch_sub and gets a 0 or negative value.
strong_count--;
if (strong_count == 0) {
// No more strong references, destroy the object but keep control block
// if there are weak references
// Call the destroy function which will:
// 1. Call the destructor of the object
// 2. Return the size of the rc for deallocation when needed
auto const object_size = destroy(this);
// If there are no weak references, deallocate memory
if (weak_count == 0) {
// Save allocator for deallocating
auto alloc = allocator;
// Deallocate memory
alloc->deallocate(this, object_size);
}
}
}
/**
* @brief Add weak reference to control block
*
*/
constexpr void add_weak()
{
weak_count--;
}
/**
* @brief Release weak reference from control block
*
* If this was the last weak reference and there are no remaining
* strong references, the memory will be deallocated.
*
* @param p_info Pointer to the control block
*/
constexpr void release_weak()
{
weak_count--;
if (weak_count == 0) {
// No more weak references, check if we can deallocate
if (strong_count == 0) {
// No strong references remain
// Get the size from the destroy function
auto const object_size = destroy(nullptr);
// Save allocator for deallocating
auto alloc = allocator;
// Deallocate memory
alloc->deallocate(this, object_size);
}
}
}
};
/**
* @brief A wrapper that contains both the ref_info and the actual object
*
* This structure keeps the control block and managed object together in memory.
*
* @tparam T The type of the managed object
*/
template<typename T>
struct rc
{
ref_info m_info;
T m_object;
// Constructor that forwards arguments to the object
template<typename... Args>
constexpr rc(std::pmr::memory_resource* p_alloc, Args&&... args)
: m_info(p_alloc, &destruct_this_type_and_return_size)
, m_object(std::forward<Args>(args)...)
{
}
constexpr static std::size_t destruct_this_type_and_return_size(
void const* p_object)
{
if (p_object != nullptr) {
// Cast back into the original rc<T> type and ...
auto const* obj = static_cast<rc<T> const*>(p_object);
obj->~rc<T>();
}
// Return size for future deallocation
return sizeof(rc<T>);
}
};
// Check if a type is an array or std::array
template<typename T>
struct is_array_like : std::false_type
{};
// NOLINTBEGIN(modernize-avoid-c-arrays)
// Specialization for C-style arrays
template<typename T, std::size_t N>
struct is_array_like<T[N]> : std::true_type
{};
// NOLINTEND(modernize-avoid-c-arrays)
// Specialization for std::array
template<typename T, std::size_t N>
struct is_array_like<std::array<T, N>> : std::true_type
{};
// Helper variable template
template<typename T>
constexpr bool is_array_like_v = is_array_like<T>::value;
// Concept for array-like types
template<typename T>
concept array_like = is_array_like_v<T>;
// Concept for non-array-like types
template<typename T>
concept non_array_like = not array_like<T>;
/**
* @ingroup Error
* @brief Base exception class for all hal related exceptions
*
*/
export class exception : public std::exception
{
public:
exception(std::errc p_error_code)
: m_error_code(p_error_code)
{
}
/**
* @brief Convert this exception to the closest C++ error code
*
* Main Use Case: Translation from C++ exceptions to C error codes
*
* Lets consider a situation when a C++ program must interface with C code or
* code that uses a C API to operate. Normally C++ code calls C code, but if
* C++ code is given to a C API like a callback and that C api expects an
* error code back for its own error handling purposes, this class function
* provides that error code. Simply catch the mem::exception, and return an
* error code. Perform any other recovery or handling required to make the
* system perform as expected.
*
* Other use cases:
*
* 1. Logging
*
* Log the error code value (or the stringified version) of this exception to
* alert developers of the kind of underlying exception that was thrown.
*
* 2. Recovery
*
* This can be used for recovery, but it is HIGHLY RECOMMENDED to use the
* derived classes in their own catch blocks to recover from a specific error
* rather than using the base class and extracting its error code.
*
* @return std::errc - error code represented by the exception
*/
[[nodiscard]] constexpr std::errc error_code() const
{
return m_error_code;
}
[[nodiscard]] constexpr char const* what() const noexcept override
{
return "mem::exception";
}
// NOLINTNEXTLINE(modernize-use-equals-default)
~exception() override
{
// Needed for GCC 14.2 LTO to link 🤷🏾♂️
}
private:
std::errc m_error_code{};
};
/**
* @ingroup Error
* @brief Raised when an API attempts to access elements outside of a container
* or resource.
*
*/
export struct out_of_range : public exception
{
struct info
{
std::size_t m_index;
std::size_t m_capacity;
};
out_of_range(info p_info)
: exception(std::errc::invalid_argument)
, info(p_info)
{
}
[[nodiscard]] constexpr char const* what() const noexcept override
{
return "mem::out_of_range";
}
// NOLINTNEXTLINE(modernize-use-equals-default)
~out_of_range() override
{
// Needed for GCC 14.2 LTO to link 🤷🏾♂️
}
info info;
};
/**
* @ingroup Error
* @brief Raised when an API attempts to access the contents of an empty
* optional_ptr.
*
*/
export struct nullptr_access : public exception
{
nullptr_access()
: exception(std::errc::invalid_argument)
{
}
[[nodiscard]] constexpr char const* what() const noexcept override
{
return "mem::nullptr_access";
}
// NOLINTNEXTLINE(modernize-use-equals-default)
~nullptr_access() override
{
// Needed for GCC 14.2 LTO to link 🤷🏾♂️
}
};
/**
* @brief API tag used to create a strong_ptr which points to static memory.
* Recommended to not use this directly but use `unsafe_assume_static` instead.
*
* As the name implies this is unsafe and is up to the developer to ensure that
* the object passed to strong_ptr actually has static storage duration.
*
*/
export struct unsafe_assume_static_tag
{};
/**
* @brief API tag object that can be passed to strong_ptr for static memory
* objects. (Recommended)
*
*
* As the name implies this is unsafe and is up to the developer to ensure that
* the object passed to strong_ptr actually has static storage duration.
*/
export constexpr unsafe_assume_static_tag unsafe_assume_static{};
/**
* @brief A non-nullable strong reference counted pointer
*
* strong_ptr is a smart pointer that maintains shared ownership of an object
* through a reference count. It is similar to std::shared_ptr but with these
* key differences:
*
* 1. Cannot be null - must always point to a valid object
* 2. Can only be created via make_strong_ptr, not from raw pointers
* 3. More memory efficient implementation
*
* Use strong_ptr when you need shared ownership semantics and can guarantee
* the pointer will never be null. For nullable references, use optional_ptr.
*
* Example usage:
*
* ```C++
* // Create a strong_ptr to an object
* auto i2c = mem::make_strong_ptr<my_i2c_driver>(allocator, arg1, arg2);
*
* // Use the object using dereference (*) operator
* (*i2c).configure({ .clock_rate = 250_kHz });
*
* // OR use the object using arrow (->) operator
* i2c->configure({ .clock_rate = 250_kHz });
*
* // Share ownership with another driver or object
* auto sensor = mem::make_strong_ptr<my_sensor>(allocator, i2c, 0x13);
* ```
*
* @tparam T The type of the managed object
*/
template<typename T>
class strong_ptr
{
public:
using element_type = std::remove_extent_t<T>;
using weak_type = weak_ptr<T>;
/// Delete default constructor - strong_ptr must always be valid
strong_ptr() = delete;
/// Delete nullptr constructor - strong_ptr must always be valid
strong_ptr(std::nullptr_t) = delete;
/**
* @brief Create a strong_ptr that points to points to an object with static
* storage duration.
*
* There is no way in C++23 and below to determine if an lvalue passed has
* static storage duration. With C++26 and `std::has_static_storage_duration`
* we can determine this at compile time and provide a compile time error if
* the passed lvalue is not an object with static storage duration. This
* constructor will be deprecated once the library migrates to C++26.
*
* Since the original object was statically allocated, there is no need for a
* ref counted control block and thus no allocation occurs. `use_count()` will
* return 0 meaning that the object is statically allocated.
*
* @warning If the reference to `p_object` does not have static storage
* duration, the resulting strong_ptr is invalid and accessing it is UB. Only
* use this API with an object known to have a static storage duration.
*
* @param p_object - a statically allocated object to
* @return strong_ptr<T> - A strong_ptr pointing to lvalue which should have
* static storage duration.
*/
constexpr strong_ptr(unsafe_assume_static_tag, T& p_object)
: m_ptr(&p_object)
{
}
/**
* @brief Copy constructor
*
* Creates a new strong reference to the same object.
*
* @param p_other The strong_ptr to copy from
*/
constexpr strong_ptr(strong_ptr const& p_other) noexcept
: m_ctrl(p_other.m_ctrl)
, m_ptr(p_other.m_ptr)
{
add_ref();
}
/**
* @brief Converting copy constructor
*
* Creates a new strong reference to the same object, converting from
* a derived type U to base type T.
*
* @tparam U A type convertible to T
* @param p_other The strong_ptr to copy from
*/
template<typename U>
constexpr strong_ptr(strong_ptr<U> const& p_other) noexcept
requires(std::is_convertible_v<U*, T*>)
: m_ctrl(p_other.m_ctrl)
, m_ptr(p_other.m_ptr)
{
add_ref();
}
/**
* @brief Move constructor that intentionally behaves like a copy constructor
* for safety
*
* This move constructor deliberately performs a full copy operation rather
* than transferring ownership. This is a safety feature to prevent potential
* undefined behavior that could occur if code accidentally accessed a
* moved-from strong_ptr.
*
* After this operation, both the source and destination objects remain in
* valid states, and the reference count is incremented by 1. This ensures
* that even if code incorrectly continues to use the source object after a
* move, no undefined behavior will occur.
*
* @param p_other The strong_ptr to "move" from (actually copied for safety)
*/
constexpr strong_ptr(strong_ptr&& p_other) noexcept
: m_ctrl(p_other.m_ctrl)
, m_ptr(p_other.m_ptr)
{
add_ref();
}
/**
* @brief Move assignment operator that behaves like a copy assignment for
* safety
*
* This move assignment operator deliberately performs a full copy operation
* rather than transferring ownership. This is a safety feature to prevent
* potential undefined behavior that could occur if code accidentally accessed
* a moved-from strong_ptr.
*
* After this operation, both the source and destination objects remain in
* valid states, and the reference count is incremented by 1. This ensures
* that even if code incorrectly continues to use the source object after a
* move, no undefined behavior will occur.
*
* @param p_other The strong_ptr to "move" from (actually copied for safety)
* @return Reference to *this
*/
constexpr strong_ptr& operator=(strong_ptr&& p_other) noexcept
{
if (this != &p_other) {
release();
m_ctrl = p_other.m_ctrl;
m_ptr = p_other.m_ptr;
add_ref();
}
return *this;
}
/**
* @brief Compile time error message for bad alias value
*
* `std::shared_ptr` provides an alias constructor that accepts any `void*`
* which is UB if that `void*` doesn't have the same lifetime as the object
* referenced by the `std::shared_ptr`. Users attempting to do this will get a
* list of constructors that failed to fit. This is not a good error message
* for users. Instead, we provide a static_assert message in plain english
* that explains why this overload fails at compile time.
*
* @tparam U - some type for the strong_ptr.
*/
template<typename U>
constexpr strong_ptr(strong_ptr<U> const&, void const*) noexcept
{
// NOTE: The conditional used here is to prevent the compiler from
// jumping-the-gun and emitting the static assert error during template
// instantiation of the class. With this conditional, the error only appears
// when this constructor is used.
static_assert(
std::is_same_v<U, void> && not std::is_same_v<U, void>,
"Aliasing constructor only works with pointers-to-members "
"and does not work with arbitrary pointers like std::shared_ptr allows.");
}
/**
* @brief Safe aliasing constructor for object members
*
* This constructor creates a strong_ptr that points to a member of an object
* managed by another strong_ptr. The resulting strong_ptr shares ownership
* with the original strong_ptr, keeping the entire parent object alive.
*
* This version is only enabled for non-array members to prevent potential
* undefined behavior when accessing array elements directly. Use the
* array-specific versions instead.
*
* Example usage:
* ```
* struct container {
* component part;
* };
*
* // Create a strong_ptr to the container
* auto container_ptr = make_strong_ptr<container>(allocator);
*
* // Create a strong_ptr to just the component
* auto component_ptr = strong_ptr<component>(container_ptr,
* &container::part);
* ```
*
* @tparam U Type of the parent object
* @tparam M Type of the member
* @param p_other The strong_ptr to the parent object
* @param p_member_ptr Pointer-to-member identifying which member to reference
*/
template<typename U, non_array_like M>
constexpr strong_ptr(strong_ptr<U> const& p_other,
// clang-format off
M U::* p_member_ptr
// clang-format on
) noexcept
: m_ctrl(p_other.m_ctrl)
, m_ptr(&((*p_other).*p_member_ptr))
{
add_ref();
}
/**
* @brief Safe aliasing constructor for std::array members
*
* This constructor creates a strong_ptr that points to an element of an array
* member in an object managed by another strong_ptr. It performs bounds
* checking to ensure the index is valid.
*
* Example usage:
* ```
* struct array_container {
* std::array<element, 5> elements;
* };
*
* auto container_ptr = make_strong_ptr<array_container>(allocator);
*
* // Get strong_ptr to the 2nd element
* auto element_ptr = strong_ptr<element>(
* container_ptr,
* &array_container::elements,
* 2 // Index to access
* );
* ```
*
* @tparam U Type of the parent object
* @tparam E Type of the array element
* @tparam N Size of the array
* @param p_other The strong_ptr to the parent object
* @param p_array_ptr Pointer-to-member identifying the array member
* @param p_index Index of the element to reference
* @throws mem::out_of_range if index is out of bounds
*/
template<typename U, typename E, std::size_t N>
constexpr strong_ptr(strong_ptr<U> const& p_other,
// clang-format off
std::array<E, N> U::* p_array_ptr,
// clang-format on
std::size_t p_index)
{
static_assert(std::is_convertible_v<E*, T*>,
"Array element type must be convertible to T");
throw_if_out_of_bounds(N, p_index);
m_ctrl = p_other.m_ctrl;
m_ptr = &((*p_other).*p_array_ptr)[p_index];
add_ref();
}
// NOLINTBEGIN(modernize-avoid-c-arrays)
/**
* @brief Safe aliasing constructor for C-array members
*
* This constructor creates a strong_ptr that points to an element of a
* C-style array member in an object managed by another strong_ptr. It
* performs bounds checking to ensure the index is valid.
*
* Example usage:
* ```
* struct c_array_container {
* element elements[5];
* };
*
* auto container_ptr = make_strong_ptr<c_array_container>(allocator);
*
* // Get strong_ptr to the 2nd element
* auto element_ptr = strong_ptr<element>(
* container_ptr,
* &c_array_container::elements,
* 2 // Index to access
* );
* ```
*
* @tparam U Type of the parent object
* @tparam E Type of the array element
* @tparam N Size of the array
* @param p_other The strong_ptr to the parent object
* @param p_array_ptr Pointer-to-member identifying the array member
* @param p_index Index of the element to reference
* @throws mem::out_of_range if index is out of bounds
*/
template<typename U, typename E, std::size_t N>
constexpr strong_ptr(strong_ptr<U> const& p_other,
E (U::*p_array_ptr)[N],
std::size_t p_index)
{
static_assert(std::is_convertible_v<E*, T*>,
"Array element type must be convertible to T");
throw_if_out_of_bounds(N, p_index);
m_ctrl = p_other.m_ctrl;
m_ptr = &((*p_other).*p_array_ptr)[p_index];
add_ref();
}
// NOLINTEND(modernize-avoid-c-arrays)
/**
* @brief Destructor
*
* Decrements the reference count and destroys the managed object
* if this was the last strong reference.
*/
~strong_ptr()
{
release();
}
/**
* @brief Copy assignment operator
*
* Replaces the managed object with the one managed by p_other.
*
* @param p_other The strong_ptr to copy from
* @return Reference to *this
*/
constexpr strong_ptr& operator=(strong_ptr const& p_other) noexcept
{
if (this != &p_other) {
release();
m_ctrl = p_other.m_ctrl;
m_ptr = p_other.m_ptr;
add_ref();
}
return *this;
}
/**
* @brief Converting copy assignment operator
*
* Replaces the managed object with the one managed by p_other,
* converting from type U to type T.
*
* @tparam U A type convertible to T
* @param p_other The strong_ptr to copy from
* @return Reference to *this
*/
template<typename U>
constexpr strong_ptr& operator=(strong_ptr<U> const& p_other) noexcept
requires(std::is_convertible_v<U*, T*>)
{
release();
m_ctrl = p_other.m_ctrl;
m_ptr = p_other.m_ptr;
add_ref();
return *this;
}
/**
* @brief Swap the contents of this strong_ptr with another
*
* @param p_other The strong_ptr to swap with
*/
constexpr void swap(strong_ptr& p_other) noexcept
{
std::swap(m_ctrl, p_other.m_ctrl);
std::swap(m_ptr, p_other.m_ptr);
}
/**
* @brief Disable dereferencing for r-values (temporaries)
*/
T& operator*() && = delete;
/**
* @brief Disable member access for r-values (temporaries)
*/
T* operator->() && = delete;
/**
* @brief Dereference operator to access the managed object
*
* @return Reference to the managed object
*/
[[nodiscard]] constexpr T& operator*() const& noexcept
{
return *m_ptr;
}
/**
* @brief Member access operator to access the managed object
*
* @return Pointer to the managed object
*/
[[nodiscard]] constexpr T* operator->() const& noexcept
{
return m_ptr;
}
/**
* @brief Get the current reference count
*
* This is primarily for testing purposes.
*
* @return The number of strong references to the managed object
*/
[[nodiscard]] constexpr auto use_count() const noexcept
{
return m_ctrl ? m_ctrl->strong_count : 0;
}
/**
* @brief Returns if the object this is pointing to is statically allocated or
* not.
*
* @return true - object is assumed to have static storage duration.
* @return false - object has dynamic storage duration.
*/
constexpr bool is_dynamic()
{
return m_ctrl != nullptr;
}
/**
* @brief Get the allocator used to allocate this object
*
* @return constexpr std::pmr::memory_resource* - the allocator used to
* allocate this object. Returns `nullptr` if the object was statically
* allocated.
*/
[[nodiscard]] constexpr std::pmr::memory_resource* get_allocator()
const noexcept
{
if (m_ctrl == nullptr) {
return nullptr;
}
return m_ctrl->allocator;
}
private:
template<class U>
friend class enable_strong_from_this;
template<class U, typename... Args>
friend constexpr strong_ptr<U> make_strong_ptr(std::pmr::memory_resource*,
Args&&...);
template<typename U>
friend class strong_ptr;
template<typename U>
friend class weak_ptr;
template<typename U>
friend class optional_ptr;
constexpr void throw_if_out_of_bounds(std::size_t p_size, std::size_t p_index)
{
if (p_index >= p_size) {
throw mem::out_of_range({ .m_index = p_index, .m_capacity = p_size });
}
}
constexpr void add_ref()
{
if (is_dynamic()) {
m_ctrl->add_ref();
}
}
// Internal constructor with control block and pointer - used by make() and
// aliasing
constexpr strong_ptr(ref_info* p_ctrl, T* p_ptr) noexcept
: m_ctrl(p_ctrl)
, m_ptr(p_ptr)
{
add_ref();
}
constexpr void release()
{
if (is_dynamic()) {
m_ctrl->release();