aboutsummaryrefslogtreecommitdiff
path: root/libs/kstd/kstd/bits/shared_ptr.hpp
blob: 638fccf3c5a0f70449be6c599aee00822e854f1c (plain)
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
#ifndef KSTD_BITS_SHARED_PTR_HPP
#define KSTD_BITS_SHARED_PTR_HPP

#include <array>
#include <atomic>
#include <compare>
#include <concepts>
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>

// IWYU pragma: private, include <kstd/memory.hpp>

namespace kstd
{

  namespace bits
  {
    //! The type-erased base for the control block of shared and weak pointers.
    struct shared_ptr_control_block_base
    {
      constexpr shared_ptr_control_block_base(std::size_t strong, std::size_t weak)
          : m_strong_count(strong)
          , m_weak_count(weak)
      {}

      //! Virtual destructor to ensure correct deletion through pointer to base.
      constexpr virtual ~shared_ptr_control_block_base() = default;

      //! Increase the strong reference count on this control block.
      auto acquire_shared() noexcept -> void
      {
        m_strong_count.fetch_add(1, std::memory_order_relaxed);
      }

      //! Increase the weak reference count on this control block.
      auto acquire_weak() noexcept -> void
      {
        m_weak_count.fetch_add(1, std::memory_order_relaxed);
      }

      //! Try to increase the strong reference count on this control block.
      //!
      //! If the managed object is already being disposed, nothing happens.
      //!
      //! @return true iff. the strong count was increased, false otherwise.
      auto try_acquire_shared() noexcept -> bool
      {
        auto current = m_strong_count.load(std::memory_order_relaxed);
        while (current != 0)
        {
          if (m_strong_count.compare_exchange_weak(current, current + 1, std::memory_order::acquire,
                                                   std::memory_order::relaxed))
          {
            return true;
          }
        }
        return false;
      }

      //! Decrease the strong reference count.
      //!
      //! If, as part of executing this operation, the strong reference count hits 0, the managed object will be
      //! destroyed.
      auto release_shared() -> void
      {
        if (m_strong_count.fetch_sub(1, std::memory_order::acq_rel) == 1)
        {
          destroy_object();
          release_weak();
        }
      }

      auto release_weak() -> void
      {
        if (m_weak_count.fetch_sub(1, std::memory_order::acq_rel) == 1)
        {
          delete this;
        }
      }

      [[nodiscard]] auto strong_count() const noexcept -> std::size_t
      {
        return m_strong_count.load(std::memory_order::relaxed);
      }

    protected:
      //! Destroy the managed object.
      //!
      //! It is the responsibility of the derived control block to ensure the managed object is correctly deleted.
      constexpr virtual auto destroy_object() -> void = 0;

    private:
      std::atomic<std::size_t> m_strong_count;
      std::atomic<std::size_t> m_weak_count;
    };

    //! The control block used by shared pointers and weak pointers.
    template<typename OriginalType, typename Deleter>
    struct shared_ptr_control_block final : shared_ptr_control_block_base
    {
      using deleter = Deleter;
      using pointer = OriginalType *;

      shared_ptr_control_block(pointer pointer, deleter deleter)
          : shared_ptr_control_block_base{1, 1}
          , m_deleter{deleter}
          , m_pointer{pointer}
      {}

      constexpr auto destroy_object() -> void override
      {
        m_deleter(m_pointer);
      }

    private:
      [[no_unique_address]] deleter m_deleter;
      pointer m_pointer;
    };

    template<typename ObjectType>
    struct make_shared_control_block final : shared_ptr_control_block_base
    {
      template<typename... Args>
      explicit make_shared_control_block(Args &&... args)
          : shared_ptr_control_block_base{1, 1}
      {
        std::construct_at(reinterpret_cast<ObjectType *>(m_storage.data()), std::forward<Args>(args)...);
      }

      [[nodiscard]] auto get_pointer() noexcept -> ObjectType *
      {
        return std::launder(reinterpret_cast<ObjectType *>(m_storage.data()));
      }

    protected:
      constexpr auto destroy_object() -> void override
      {
        std::destroy_at(get_pointer());
      }

    private:
      alignas(ObjectType) std::array<std::byte, sizeof(ObjectType)> m_storage;
    };

    struct weak_ptr_locked_t
    {
    } constexpr inline weak_ptr_locked{};

    struct make_shared_allocated_t
    {
    } constexpr inline make_shared_allocated{};

    template<typename Y, typename T>
    struct is_shared_pointer_ctor_compatible : std::false_type
    {
    };

    template<typename Y, typename T>
    struct is_shared_pointer_ctor_compatible<Y *, T *> : std::is_convertible<Y *, T *>
    {
    };

    template<typename U, std::size_t N>
    struct is_shared_pointer_ctor_compatible<U (*)[N], U (*)[]>  // NOLINT(modernize-avoid-c-arrays)
        : std::true_type
    {
    };

    template<typename U, std::size_t N>
    struct is_shared_pointer_ctor_compatible<U (*)[N], U const (*)[]>  // NOLINT(modernize-avoid-c-arrays)
        : std::true_type
    {
    };

    template<typename U, std::size_t N>
    struct is_shared_pointer_ctor_compatible<U (*)[N], U volatile (*)[]>  // NOLINT(modernize-avoid-c-arrays)
        : std::true_type
    {
    };

    template<typename U, std::size_t N>
    struct is_shared_pointer_ctor_compatible<U (*)[N], U volatile const (*)[]>  // NOLINT(modernize-avoid-c-arrays)
        : std::true_type
    {
    };
  }  // namespace bits

  template<typename T>
  struct shared_ptr;

  //! A pointer type to hold a non-owning reference to an object managed by a share pointer.
  //!
  //! @tparam T The type of the object referenced by this weak pointer.
  template<typename T>
  struct weak_ptr
  {
    template<typename U>
    friend struct shared_ptr;

    template<typename U>
    friend struct weak_ptr;

    template<typename U, typename... Args>
    friend auto make_shared(Args &&... args) -> shared_ptr<U>;

    //! The type of object referred to by this instance.
    using element_type = std::remove_extent_t<T>;
    using pointer = element_type *;

    //! Construct an empty weak pointer.
    constexpr weak_ptr() noexcept
        : m_pointer(nullptr)
        , m_control_block(nullptr)
    {}

    //! Construct a weak pointer which shares ownership of the object managed by other.
    constexpr weak_ptr(weak_ptr const & other) noexcept
        : m_pointer(other.m_pointer)
        , m_control_block(other.m_control_block)
    {
      if (m_control_block != nullptr)
      {
        m_control_block->acquire_weak();
      }
    }

    //! Construct a weak pointer which shares ownership of the object managed by other.
    template<typename Y>
      requires bits::is_shared_pointer_ctor_compatible<Y *, T *>::value
    constexpr weak_ptr(weak_ptr<Y> const & other) noexcept
        : m_pointer(other.m_pointer)
        , m_control_block(other.m_control_block)
    {
      if (m_control_block != nullptr)
      {
        m_control_block->acquire_weak();
      }
    }

    //! Construct a weak pointer which shares ownership of the object managed by other.
    template<typename Y>
      requires bits::is_shared_pointer_ctor_compatible<Y *, T *>::value
    constexpr weak_ptr(shared_ptr<Y> const & other) noexcept
        : m_pointer(other.m_pointer)
        , m_control_block(other.m_control_block)
    {
      if (m_control_block != nullptr)
      {
        m_control_block->acquire_weak();
      }
    }

    //! Construct a weak pointer which takes ownership of the object managed by other.
    constexpr weak_ptr(weak_ptr && other) noexcept
        : m_pointer(std::exchange(other.m_pointer, nullptr))
        , m_control_block(std::exchange(other.m_control_block, nullptr))
    {}

    //! Construct a weak pointer which takes ownership of the object managed by other.
    template<typename Y>
      requires std::is_convertible_v<Y *, T *>
    constexpr weak_ptr(weak_ptr<Y> && other) noexcept
        : m_pointer(std::exchange(other.m_pointer, nullptr))
        , m_control_block(std::exchange(other.m_control_block, nullptr))
    {}

    //! Replace the object managed by this pointer with the one managed by another one.
    auto operator=(weak_ptr const & other) noexcept -> weak_ptr &
    {
      weak_ptr<T>{other}.swap(*this);
      return *this;
    }

    //! Replace the object managed by this pointer with the one managed by another one.
    template<typename Y>
    constexpr auto operator=(weak_ptr<Y> const & other) noexcept -> weak_ptr &
    {
      weak_ptr<T>{other}.swap(*this);
      return *this;
    }

    //! Replace the object managed by this pointer with the one managed by shared pointer.
    template<typename Y>
    constexpr auto operator=(shared_ptr<Y> const & other) noexcept -> weak_ptr &
    {
      weak_ptr<T>{other}.swap(*this);
      return *this;
    }

    //! Replace the object managed by this pointer with the one managed by another one.
    auto operator=(weak_ptr && other) noexcept -> weak_ptr &
    {
      weak_ptr<T>{std::move(other)}.swap(*this);
      return *this;
    }

    //! Replace the object managed by this pointer with the one managed by another one.
    template<typename Y>
    auto operator=(weak_ptr<Y> && other) noexcept -> weak_ptr &
    {
      weak_ptr<T>{std::move(other)}.swap(*this);
      return *this;
    }

    //! Destroy this pointer, cleaning up resources if necessary.
    ~weak_ptr()
    {
      if (m_control_block)
      {
        m_control_block->release_weak();
      }
    }

    //! Release the reference to the object managed by this weak pointer.
    constexpr auto reset() -> void
    {
      weak_ptr<T>{}.swap(*this);
    }

    //! Exchange the ownership of the object managed by this pointer with the one of another one.
    constexpr auto swap(weak_ptr & other) -> void
    {
      std::ranges::swap(m_pointer, other.m_pointer);
      std::ranges::swap(m_control_block, other.m_control_block);
    }

    //! Exchange the ownership of the object managed by weak pointer objects.
    constexpr auto friend swap(weak_ptr & lhs, weak_ptr & rhs) noexcept -> void
    {
      return lhs.swap(rhs);
    }

    //! Get the number of shared pointers that share ownership with the object managed by this weak pointer.
    [[nodiscard]] constexpr auto use_count() const noexcept -> long
    {
      if (m_control_block)
      {
        return m_control_block->strong_count();
      }
      return 0;
    }

    //! Check if the object managed by this weak pointer has already been deleted.
    [[nodiscard]] constexpr auto expired() const noexcept -> bool
    {
      return use_count() == 0;
    }

    //! Create a shared pointer that manages the object, if any, managed by this weak pointer.
    [[nodiscard]] auto lock() const -> shared_ptr<T>
    {
      if (m_control_block && m_control_block->try_acquire_shared())
      {
        return shared_ptr<T>{m_pointer, m_control_block, bits::weak_ptr_locked};
      }
      return shared_ptr<T>{};
    }

    //! Check if this weak pointer precedes another one in owner-based order.
    template<typename Y>
    [[nodiscard]] auto owner_before(weak_ptr<Y> const & other) const noexcept -> bool
    {
      return m_control_block < other.m_control_block;
    }

    //! Check if this weak pointer precedes a shared pointer in owner-based order.
    template<typename Y>
    [[nodiscard]] auto owner_before(shared_ptr<Y> const & other) const noexcept -> bool
    {
      return m_control_block < other.m_control_block;
    }

  private:
    pointer m_pointer;
    bits::shared_ptr_control_block_base * m_control_block;
  };

  //! Deduction guide for construction from a shared pointer.
  template<typename T>
  weak_ptr(shared_ptr<T>) -> weak_ptr<T>;

  /**
   * @brief enable_shared_from_this is a base class that allows an object that is currently managed by a shared_ptr to
   * create additional shared_ptr instances that share ownership of the same object. This is usefl when you want to
   * create shared_ptr instances in a member function of the object.
   *
   * @tparam T The type of the managed object.
   */
  template<typename T>
  struct enable_shared_from_this
  {
    template<typename U>
    friend struct shared_ptr;

    friend T;

  public:
    /**
     * @brief Returns a shared_ptr that shares ownership of *this.
     */
    auto shared_from_this() -> shared_ptr<T>
    {
      return shared_ptr<T>(m_weak_this);
    }

    /**
     * @brief Returns a shared_ptr that shares ownership of *this.
     */
    auto shared_from_this() const -> shared_ptr<T const>
    {
      return shared_ptr<T const>(m_weak_this);
    }

  private:
    enable_shared_from_this() = default;

    enable_shared_from_this(enable_shared_from_this const &) {}

    auto operator=(enable_shared_from_this const &) -> enable_shared_from_this &
    {
      return *this;
    }

    ~enable_shared_from_this() = default;

    void internal_assign_ptr(shared_ptr<T> const & ptr) const
    {
      m_weak_this = ptr;
    }

    mutable weak_ptr<T> m_weak_this{};  ///< Weak pointer to the object, used for shared_from_this functionality.
  };

  /**
   * @brief Shared_pointer is a smart pointer that retains shared ownership of an object through a pointer. Several
   * shared_ptr objects may own the same object. The object is destroyed and its memory deallocated when either of
   * the following happens: the last remaining shared_ptr owning the object is destroyed; the last remaining
   * shared_ptr owning the object is assigned another pointer via operator= or reset(). A
   * shared_ptr can share ownership of an object while storing a pointer to another object. This feature can be used
   * to point to member objects while owning the object they belong to. The stored pointer is the one accessed by get(),
   * the dereference and the comparison operators. The managed pointer is the one passed to the deleter when use count
   * reaches zero.
   *
   * @tparam T The type of the managed object.
   */
  template<typename T>
  struct shared_ptr
  {
    template<typename U>
    friend struct shared_ptr;

    template<typename U>
    friend struct weak_ptr;

    template<typename U, typename... Args>
    friend auto make_shared(Args &&... args) -> shared_ptr<U>;

    //! The type of object referred to by this instance.
    using element_type = std::remove_extent_t<T>;
    using weak_type = weak_ptr<T>;

    /**
     * @brief Construct an empty shared_ptr.
     */
    constexpr shared_ptr() noexcept
        : m_pointer(nullptr)
        , m_control_block(nullptr)
    {}

    /**
     * @brief Construct an empty shared_ptr from nullptr.
     */
    constexpr shared_ptr(std::nullptr_t) noexcept
        : m_pointer(nullptr)
        , m_control_block(nullptr)
    {}

    /**
     * @brief Constructor.
     *
     * @param pointer A pointer to an object to manage (default is nullptr).
     */
    template<typename U>
      requires(std::is_convertible_v<U *, T *>)
    constexpr explicit shared_ptr(U * pointer)
        : m_pointer(pointer)
        , m_control_block(
              new bits::shared_ptr_control_block<U, std::default_delete<U>>{pointer, std::default_delete<U>{}})
    {
      assign_enable_shared_from_this(pointer);
    }

    //! Construct a new shared pointer managing the given object with the given deleter.
    //!
    //! @param pointer A pointer to the object to manage.
    //! @param deleter The deleter to use when destroying the object.
    template<typename Y, typename Deleter>
      requires(std::is_convertible_v<Y *, T *>)
    constexpr shared_ptr(Y * pointer, Deleter deleter)
        : m_pointer(pointer)
        , m_control_block(new bits::shared_ptr_control_block<Y, Deleter>{pointer, deleter})
    {
      assign_enable_shared_from_this(pointer);
    }

    /**
     * @brief Construct a shared_ptr from a weak_ptr. If other is not expired, constructs a shared_ptr which shares
     * ownership of the object managed by other. Otherwise, constructs an empty shared_ptr.
     *
     * @param other The weak_ptr to construct from.
     */
    template<typename U>
      requires(std::is_convertible_v<U *, T *>)
    explicit shared_ptr(weak_ptr<U> const & other)
        : m_pointer(nullptr)
        , m_control_block(nullptr)
    {
      if (other.m_control_block && other.m_control_block->try_acquire_shared())
      {
        m_pointer = other.m_pointer;
        m_control_block = other.m_control_block;
      }
    }

    //! Aliasing constructor.
    //!
    //! @tparam U The type of the object managed by other.
    //! @param other The shared_ptr to share ownership with.
    //! @param pointer The pointer this shared_ptr should own.
    template<typename Y>
    shared_ptr(shared_ptr<Y> const & other, T * pointer) noexcept
        : m_pointer{pointer}
        , m_control_block{other.m_control_block}
    {
      if (m_control_block != nullptr)
      {
        m_control_block->acquire_shared();
      }
    }

    /**
     * @brief Copy constructor.
     *
     * @param other The shared_ptr to copy from.
     */
    shared_ptr(shared_ptr const & other) noexcept
        : m_pointer(other.m_pointer)
        , m_control_block(other.m_control_block)
    {
      if (m_control_block != nullptr)
      {
        m_control_block->acquire_shared();
      }
    }

    /**
     * @brief Converting copy constructor for compatible shared_ptr types.
     *
     * @tparam U Source pointer element type.
     * @param other The shared_ptr to copy from.
     */
    template<typename U>
      requires(std::is_convertible_v<U *, T *>)
    shared_ptr(shared_ptr<U> const & other) noexcept
        : m_pointer(other.m_pointer)
        , m_control_block(other.m_control_block)
    {
      if (m_control_block != nullptr)
      {
        m_control_block->acquire_shared();
      }
    }

    /**
     * @brief Move constructor.
     *
     * @param other The shared_ptr to move from.
     */
    shared_ptr(shared_ptr && other) noexcept
        : m_pointer(std::exchange(other.m_pointer, nullptr))
        , m_control_block(std::exchange(other.m_control_block, nullptr))
    {}

    /**
     * @brief Converting move constructor for compatible shared_ptr types.
     *
     * @tparam U Source pointer element type.
     * @param other The shared_ptr to move from.
     */
    template<typename U>
      requires(std::is_convertible_v<U *, T *>)
    shared_ptr(shared_ptr<U> && other) noexcept
        : m_pointer(std::exchange(other.m_pointer, nullptr))
        , m_control_block(std::exchange(other.m_control_block, nullptr))
    {}

    /**
     * @brief Copy assignment operator. Replaces the managed object with the one managed by r. Shares ownership of the
     * object managed by r. If r manages no object, *this manages no object too. Equivalent to
     * shared_ptr<T>(r).swap(*this).
     *
     * @param other Another smart pointer to share the ownership with.
     * @return Reference to this shared pointer.
     */
    auto operator=(shared_ptr const & other) -> shared_ptr &
    {
      shared_ptr<T>(other).swap(*this);
      return *this;
    }

    /**
     * @brief Converting copy assignment for compatible shared_ptr types.
     *
     * @tparam U Source pointer element type.
     * @param other Another smart pointer to share ownership with.
     * @return Reference to this shared pointer.
     */
    template<typename U>
      requires(std::is_convertible_v<U *, T *>)
    auto operator=(shared_ptr<U> const & other) -> shared_ptr &
    {
      shared_ptr<T>(other).swap(*this);
      return *this;
    }

    /**
     * @brief Move assignment operator. Move-assigns a shared_ptr from r. After the assignment, *this contains a copy of
     * the previous state of r, and r is empty. Equivalent to shared_ptr<T>(std::move(r)).swap(*this).
     *
     * @param other Another smart pointer to acquire the ownership from.
     * @return Reference to this shared pointer.
     */
    auto operator=(shared_ptr && other) noexcept -> shared_ptr &
    {
      shared_ptr<T>(std::move(other)).swap(*this);
      return *this;
    }

    /**
     * @brief Converting move assignment for compatible shared_ptr types.
     *
     * @tparam U Source pointer element type.
     * @param other Another smart pointer to acquire ownership from.
     * @return Reference to this shared pointer.
     */
    template<typename U>
      requires(std::is_convertible_v<U *, T *>)
    auto operator=(shared_ptr<U> && other) noexcept -> shared_ptr &
    {
      shared_ptr<T>(std::move(other)).swap(*this);
      return *this;
    }

    /**
     * @brief Reset this shared_ptr to empty via nullptr assignment.
     */
    auto operator=(std::nullptr_t) noexcept -> shared_ptr &
    {
      cleanup();
      m_pointer = nullptr;
      m_control_block = nullptr;
      return *this;
    }

    /**
     * @brief Destructor. Cleans up resources if necessary.
     */
    ~shared_ptr()
    {
      cleanup();
    }

    //! Check if two shared pointer objects point to the same object.
    //!
    //!@tparam Y, U Types of the managed objects of the shared_ptr instances being compared.
    //!@param lhs, rhs The shared_ptr instances to compare.
    //!@return true if lhs and rhs point to the same object, false otherwise.
    template<typename U>
    [[nodiscard]] constexpr auto friend operator==(shared_ptr const & lhs, shared_ptr<U> const & rhs) noexcept -> bool
    {
      return lhs.get() == rhs.get();
    }

    //! Lexicographically compare two shared pointer objects based on the objects they point to.
    //!
    //! @tparam Y, U Types of the managed objects of the shared_ptr instances being compared.
    //! @param lhs, rhs The shared_ptr instances to compare.
    //! @return The result of comparing the stored pointers of lhs and rhs using operator<=>
    template<typename U>
    [[nodiscard]] constexpr auto friend operator<=>(shared_ptr const & lhs, shared_ptr<U> const & rhs) noexcept
        -> std::strong_ordering
    {
      return std::compare_three_way{}(lhs.get(), rhs.get());
    }

    //! Check if a shared pointer points to no object.
    [[nodiscard]] constexpr friend auto operator==(shared_ptr const & lhs, std::nullptr_t) noexcept -> bool
    {
      return !lhs;
    }

    //! Lexicographically compare a shared pointer to a null pointer.
    [[nodiscard]] constexpr friend auto operator<=>(shared_ptr const & lhs, std::nullptr_t) noexcept
        -> std::strong_ordering
    {
      return std::compare_three_way{}(lhs.get(), static_cast<shared_ptr::element_type *>(nullptr));
    }

    /**
     * @brief Replaces the managed object.
     *
     * @param ptr Pointer to a new object to manage (default = nullptr).
     */
    void reset(T * ptr = nullptr)
    {
      shared_ptr<T>(ptr).swap(*this);
    }

    /**
     * @brief Exchanges the stored pointer values and the ownerships of *this and r. Reference counts, if any, are not
     * adjusted.
     *
     * @param other The shared_ptr to swap with.
     */
    void swap(shared_ptr & other)
    {
      std::ranges::swap(m_pointer, other.m_pointer);
      std::ranges::swap(m_control_block, other.m_control_block);
    }

    /**
     * @brief Dereference operator. If get() is a null pointer, the behavior is undefined.
     *
     * @return Returns the object owned by *this, equivalent to *get().
     */
    template<typename U = T>
      requires(!std::is_void_v<std::remove_cv<U>>)
    [[nodiscard]] auto operator*() const -> U &
    {
      return *m_pointer;
    }

    /**
     * @brief Member access operator.
     *
     * @return Returns a pointer to the object owned by *this, i.e. get().
     */
    [[nodiscard]] auto operator->() const -> T *
    {
      return m_pointer;
    }

    /**
     * @brief Returns a pointer to the managed object or nullptr if no object is owned.
     *
     * @return Pointer to the managed object or nullptr if no object is owned.
     */
    [[nodiscard]] auto get() const -> T *
    {
      return m_pointer;
    }

    /**
     * @brief Returns the number of different shared_ptr instances (*this included) managing the current object. If
     * there is no managed object, ​0​ is returned.
     *
     * @note Common use cases include comparison with ​0​. If use_count returns zero, the shared pointer is empty
     * and manages no objects (whether or not its stored pointer is nullptr). Comparison with 1. If use_count returns 1,
     * there are no other owners.
     *
     * @return The number of Shared_pointer instances managing the current object or ​0​ if there is no managed
     * object.
     */
    [[nodiscard]] auto use_count() const -> std::size_t
    {
      if (m_control_block != nullptr)
      {
        return m_control_block->strong_count();
      }

      return 0;
    }

    /**
     * @brief Checks whether *this owns an object, i.e. whether get() != nullptr.
     *
     * @return true if *this owns an object, false otherwise.
     */
    [[nodiscard]] explicit operator bool() const
    {
      return m_pointer != nullptr;
    }

  private:
    shared_ptr(T * pointer, bits::shared_ptr_control_block_base * control_block, bits::weak_ptr_locked_t) noexcept
        : m_pointer(pointer)
        , m_control_block(control_block)
    {}

    shared_ptr(T * pointer, bits::shared_ptr_control_block_base * control_block, bits::make_shared_allocated_t) noexcept
        : m_pointer(pointer)
        , m_control_block(control_block)
    {
      assign_enable_shared_from_this(pointer);
    }

    /**
     * @brief If the candidate type inherits from enable_shared_from_this, assigns the internal weak pointer to this
     * shared_ptr. This weak_ptr is used to implement shared_from_this functionality for the candidate type. If the
     * candidate type does not inherit from enable_shared_from_this, this function does nothing.
     *
     * @tparam U The candidate type to check for enable_shared_from_this inheritance.
     * @param candidate The candidate object to assign the internal weak pointer for.
     */
    template<typename U>
    auto assign_enable_shared_from_this(U * candidate) -> void
    {
      if constexpr (requires(U * p) { p->internal_assign_ptr(shared_ptr<U>{}); })
      {
        if (candidate != nullptr)
        {
          candidate->internal_assign_ptr(shared_ptr<U>(*this, candidate));
        }
      }
    }

    /**
     * @brief Releases ownership and deletes the object if this was the last reference to the owned managed object.
     */
    auto cleanup() -> void
    {
      if (m_control_block != nullptr)
      {
        m_control_block->release_shared();
        m_pointer = nullptr;
        m_control_block = nullptr;
      }
    }

    T * m_pointer;                                          ///< The pointed-to object.
    bits::shared_ptr_control_block_base * m_control_block;  ///< Shared control block.
  };

  /**
   * Swap the contents of lhs and rhs.
   *
   * @tparam T Type of the managed object.
   * @param lhs, rhs Shared pointers whose contents to swap.
   */
  template<typename T>
  auto swap(shared_ptr<T> & lhs, shared_ptr<T> & rhs) -> void
  {
    lhs.swap(rhs);
  }

  /**
   * @brief Constructs an object of type T and wraps it in a shared_ptr. Constructs a non-array type T. The
   * arguments args are passed to the constructor of T. This overload participates in overload resolution only if T is
   * not an array type.
   *
   * @tparam T Type of the managed object.
   * @tparam Args Argument types for T's constructor.
   * @param args List of arguments with which an instance of T will be constructed.
   * @returns Shared_pointer of an instance of type T.
   */
  template<typename T, typename... Args>
  [[nodiscard]] auto make_shared(Args &&... args) -> shared_ptr<T>
  {
    auto control_block = new bits::make_shared_control_block<T>{std::forward<Args>(args)...};
    auto pointer = control_block->get_pointer();
    return shared_ptr<T>{pointer, control_block, bits::make_shared_allocated};
  }

  template<typename T, typename U>
  [[nodiscard]] constexpr auto static_pointer_cast(shared_ptr<U> const & other) noexcept -> shared_ptr<T>
  {
    return shared_ptr<T>{other, static_cast<shared_ptr<T>::element_type *>(other.get())};
  }

  template<typename T, typename U>
  [[nodiscard]] constexpr auto static_pointer_cast(shared_ptr<U> && other) noexcept -> shared_ptr<T>
  {
    return shared_ptr<T>{std::move(other), static_cast<shared_ptr<T>::element_type *>(other.get())};
  }

  template<typename T, typename U>
  [[nodiscard]] constexpr auto dynamic_pointer_cast(shared_ptr<U> const & other) noexcept -> shared_ptr<T> = delete;

  template<typename T, typename U>
  [[nodiscard]] constexpr auto dynamic_pointer_cast(shared_ptr<U> && other) noexcept -> shared_ptr<T> = delete;

  template<typename T, typename U>
  [[nodiscard]] constexpr auto const_pointer_cast(shared_ptr<U> const & other) noexcept -> shared_ptr<T>
  {
    return shared_ptr<T>{other, const_cast<shared_ptr<T>::element_type *>(other.get())};
  }

  template<typename T, typename U>
  [[nodiscard]] constexpr auto const_pointer_cast(shared_ptr<U> && other) noexcept -> shared_ptr<T>
  {
    return shared_ptr<T>{std::move(other), const_cast<shared_ptr<T>::element_type *>(other.get())};
  }

  template<typename T, typename U>
  [[nodiscard]] constexpr auto reinterpret_pointer_cast(shared_ptr<U> const & other) noexcept -> shared_ptr<T>
  {
    return shared_ptr<T>{other, reinterpret_cast<shared_ptr<T>::element_type *>(other.get())};
  }

  template<typename T, typename U>
  [[nodiscard]] constexpr auto reinterpret_pointer_cast(shared_ptr<U> && other) noexcept -> shared_ptr<T>
  {
    return shared_ptr<T>{std::move(other), reinterpret_cast<shared_ptr<T>::element_type *>(other.get())};
  }
}  // namespace kstd

#endif