aboutsummaryrefslogtreecommitdiff
path: root/libs/kstd/include/kstd/bits/shared_ptr.hpp
blob: 893009504e15894475a1db6a84e67fce61dea24a (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
#ifndef KSTD_BITS_SHARED_PTR_HPP
#define KSTD_BITS_SHARED_PTR_HPP

#include <atomic>
#include <cstddef>
#include <type_traits>
#include <utility>

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

namespace kstd
{
  /**
   * @brief Control block for shared_ptr and weak_ptr. This control block contains the reference counts for shared
   * ownership and weak ownership. The shared_count tracks the number of shared_ptr instances that own the managed
   * object, while the weak_count tracks the number of weak_ptr instances that reference the managed object.
   * The weak_count is needed to determine when it is safe to delete the shared_control_block itself
   */
  struct shared_control_block
  {
    std::atomic<std::size_t> shared_count;
    std::atomic<std::size_t> weak_count;

    explicit shared_control_block(std::size_t shared = 1, std::size_t weak = 0)
        : shared_count(shared)
        , weak_count(weak)
    {}
  };

  template<typename T>
  struct shared_ptr;

  /**
   * @brief weak_ptr is a smart pointer that holds a non-owning weak reference to an object that is managed by
   * shared_ptr. It must be converted to shared_ptr in to be able to access the referenced object. A weak_ptr is created
   * as a copy of a shared_ptr, or as a copy of another weak_ptr. A weak_ptr is typically used to break circular
   * references between shared_ptr to avoid memory leaks. A weak_ptr does not contribute to the reference count of the
   * object, and it does not manage the lifetime of the object. If the object managed by shared_ptr is destroyed, the
   * weak_ptr becomes expired and cannot be used to access the object anymore.
   */
  template<typename T>
  struct weak_ptr
  {
    template<typename U>
    friend struct shared_ptr;

    /**
     * @brief Constructs a null weak_ptr.
     */
    weak_ptr() noexcept
        : pointer(nullptr)
        , control(nullptr)
    {}

    template<typename U>
      requires(std::is_convertible_v<U *, T *>)
    weak_ptr(shared_ptr<U> const & other)
        : pointer(other.pointer)
        , control(other.control)
    {
      if (control != nullptr)
      {
        ++(control->weak_count);
      }
    }

    /**
     * @brief Copy constructor. Constructs a weak_ptr which shares ownership of the object managed by other.
     */
    weak_ptr(weak_ptr const & other)
        : pointer(other.pointer)
        , control(other.control)
    {
      if (control != nullptr)
      {
        ++(control->weak_count);
      }
    }

    /**
     * @brief Move constructor. Constructs a weak_ptr which takes ownership of the object managed by other.
     */
    weak_ptr(weak_ptr && other) noexcept
        : pointer(other.pointer)
        , control(other.control)
    {
      other.pointer = nullptr;
      other.control = nullptr;
    }

    /**
     * @brief Assignment operator. Assigns the weak_ptr to another weak_ptr.
     */
    auto operator=(weak_ptr const & other) -> weak_ptr &
    {
      if (this != &other)
      {
        cleanup();
        pointer = other.pointer;
        control = other.control;
        if (control != nullptr)
        {
          ++(control->weak_count);
        }
      }

      return *this;
    }

    /**
     * @brief Move assignment operator. Move-assigns a weak_ptr from other.
     */
    auto operator=(weak_ptr && other) noexcept -> weak_ptr &
    {
      if (this != &other)
      {
        cleanup();
        pointer = other.pointer;
        control = other.control;
        other.pointer = nullptr;
        other.control = nullptr;
      }

      return *this;
    }

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

    /**
     * @brief Returns a shared_ptr that shares ownership of the managed object if the managed object still exists, or an
     * empty shared_ptr otherwise.
     */
    [[nodiscard]] auto lock() const -> shared_ptr<T>
    {
      return shared_ptr<T>(*this);
    }

  private:
    auto cleanup() -> void
    {
      if (control != nullptr)
      {
        if (--(control->weak_count) == 0 && control->shared_count == 0)
        {
          delete control;
        }
      }
    }

    T * pointer;
    shared_control_block * control;
  };

  /**
   * @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>(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>(weak_this);
    }

  private:
    enable_shared_from_this() = default;
    enable_shared_from_this(enable_shared_from_this const &) = default;
    auto operator=(enable_shared_from_this const &) -> enable_shared_from_this & = default;
    ~enable_shared_from_this() = default;

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

    mutable weak_ptr<T> 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;

    /**
     * @brief Construct an empty shared_ptr.
     */
    shared_ptr() noexcept
        : pointer(nullptr)
        , control(nullptr)
    {}

    /**
     * @brief Construct an empty shared_ptr from nullptr.
     */
    shared_ptr(std::nullptr_t) noexcept
        : pointer(nullptr)
        , control(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 *>)
    explicit shared_ptr(U * pointer = nullptr)
        : pointer(pointer)
        , control(pointer != nullptr ? new shared_control_block() : nullptr)
    {
      assign_enable_shared_from_this(pointer);
    }

    /**
     * @brief Constructor 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)
        : pointer(nullptr)
        , control(nullptr)