Chapter 10 : Shared Pointers, An Introduction To Atomics In C++

Key words: Shared Pointers in C++, Implementing a custom shared_ptr in C++, Atomics in C++

Topics at a glance:

  • Sharing ownership via Shared Pointers and their need
  • Atomics in Shared pointer

In this chapter, I will show you how to make a custom Shared_Ptr from our Chapter 9’s Unique_Ptr using C++’s atomics.

Shared Pointers in C++

Shared Pointers using template specialization and C++ atomics

We have seen how to implement our own Unique_Ptr class using template specialization. Unique_Ptr’s only support move semantics and no copy operation is allowed. Of course the sole purpose of Unique_Ptr is to avoid multiple owners for the same memory region at any given point of time. Using move you can only transfer ownership of memory through a Unique_Ptr. What if you want shared ownership? Then we need to use C++’s 2nd smart pointer i.e. the ‘std::shared_ptr’. Shared pointers allow multiple ownership achieved through two things:

  1. Shared pointers allow copy semantics (obviously)
  2. Shared pointers uses a reference count (use count) mechanism that tracks the current number of owners that uses the shared memory region
  3. Shared pointers will delete/release the memory back to free store only if the reference count reaches 0.

So, that is how shared pointers work.

Implementing a custom shared_ptr in C++

Now, to implement our shared pointer, let us use the Unique_Ptr code from previous chapter and rename ‘Unique_Ptr’ to ‘Shared_Ptr’. Not only that. We will need to introduce a reference counter. Reference counter cannot be a local count data to Shared_Ptr object instances as after copying the ownership Shared_Ptr should use the exact same instance of reference count to track the owners in all copies of Shared_Ptr objects.

This bring another issue. Unlike old generation computers and OS’s all modern CPU’s support actual multi-threading and parallel computing. So there can be multiple threads sharing ownership of memory through instances of Shared_Ptr’s. This will result in data race condition. And reference count is likely to be changed from different threads simultaneously. Reference count is the only thing that matters for Shared_Ptrs to delete pointer and release back the memory. So it is imperative to protect reference count from data race conditions associated with multi-threaded environments.  How to do that?

Atomics in C++

C++ gives some essential facilities to deal with issues inherent to multi-threaded environments. One we can consider here is mutex lock (mutually exclusive lock), and other is atomics. I prefer atomics here. Mutex is very difficult to apply here. As who will take care of releasing the mutex itself at the end of Shared Pointer’s life-cycle. The same mutex needs to be used for the same reference count in case of shared ownership. So why to go for all such headaches. Let us use the simple atomics. Atomics guarantees completion of execution of any operation without interruption. We’ll use C++’s std::atomic for defining the reference counter in our Shared_Ptr. So I will point out once again the key features to be implemented on Unique_Ptr to make it a Shared_Ptr class.

From Unique_Ptr to Shared_Ptr code modification:

  1. Replace Unique_Ptr to Shared_Ptr
  2. Define copy operations
  3. Implement an atomic reference count member that could be shared between copies of Shared_Ptr instances
  4. Define a use_count() member function that will return the current value of reference count

That’s it. Now, with all this information, let us implement Shared_Ptr. NOTE: For now, I am not defining any custom make_shared as we did for Unique_Ptrs. Let us use the basic new operation for constructing objects and pass the returned pointers to make Shared_Ptr instances.

Also note that I have retained all the default and custom deleters that I have used in Unique_Ptr.

Please go through the detailed and elaborated code below, and understand how the points discussed above are actually implemented.

  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
#include <iostream>
#include <atomic>

using namespace std;

// single object deleter version 
template<typename T>
struct default_deleter // default_deleter is a functor or function object 
{    
    // don't have any private/public/protected data 
    void operator()(T* ptr)
    {
        if(ptr != nullptr) // this check is very important 
        {
            cout << "default_deleter" << endl;
            // default deleter is as good as a 
            // direct delete on the pointer. 
            // There cannot be any custom cleanup here.  
            delete ptr;
        }
    }
};

// Array deleter version
template<typename T>
struct default_deleter<T[]> // default_deleter is a functor or function object 
{    
    // don't have any private/public/protected data 
    void operator()(T* ptr)
    {
        if(ptr != nullptr) // this check is very important 
        {
            cout << "default_deleter [] " << endl;
            // default deleter is as good as a 
            // direct delete on the pointer. 
            // There cannot be any custom cleanup here.  
            delete []ptr;
        }
    }
};

// An example of default template type. 
// TP's default 'type' is default_deleter<T>
// If provided, a custom deleter TP, user can either 
// install a functor object or it can be a simple
// function pointer which accepts a pointer parameter. 
template< typename T, typename TP = default_deleter<T> >
class Shared_Ptr
{
private:
    std::atomic<int*> reference_count;
    T* raw_ptr;
    TP deleter; // will get constructed anyways with default_deleter type  
public:
    explicit Shared_Ptr(T* object) : 
        raw_ptr{object}, 
        reference_count(new int(1)) // cannot use {}, use ()
    {
        cout << "Shared_Ptr created with Ref count : " << *reference_count << endl;
    }
    
    // constructor which accepts a custom deleter 
    Shared_Ptr(T* object, TP custom_deleter) : 
        raw_ptr{object}, 
        deleter{custom_deleter}, 
        reference_count(new int(1)) // cannot use {}, use ()
    {
        cout << "Shared_Ptr created with Ref count : " << *reference_count << endl;
    }
    
    ~Shared_Ptr()
    {
        if(reference_count != nullptr)
        {
            --(*reference_count);
            cout << "In Shared_Ptr Destructor Ref count : " << *reference_count << endl;
            if(*reference_count <= 0)
            {
                if(raw_ptr != nullptr)
                {
                    // call deleter
                    deleter(raw_ptr);
                }
            }
        }
    }
    
    TP& get_deleter()
    {
        return deleter;
    }
    
    // define copy operations
    Shared_Ptr(const Shared_Ptr& other_shared_ptr)
    {
        // do not create a new reference_count, copy the pointer from other_shared_ptr
        reference_count = other_shared_ptr.reference_count.load();
        if(reference_count != nullptr)
        {
            ++(*reference_count);
            cout << "In Shared_Ptr Copy Constructor Ref count : " << *reference_count << endl;
        }
        raw_ptr = other_shared_ptr.raw_ptr;
        deleter = other_shared_ptr.deleter;
    }
    
    Shared_Ptr& operator=(const Shared_Ptr& other_shared_ptr)
    {
        // do not create a new reference_count, copy the pointer from other_shared_ptr
        reference_count = other_shared_ptr.reference_count.load();
        if(reference_count != nullptr)
        {
            ++(*reference_count);
            cout << "In Shared_Ptr Copy =operator Ref count : " << *reference_count << endl;
        }
        raw_ptr = other_shared_ptr.raw_ptr;
        deleter = other_shared_ptr.deleter;
        
        return *this;
    }
    
    // Define move operations
    Shared_Ptr(Shared_Ptr&& other_shared_ptr)
    {
        // transfer the ownership of memory 
        raw_ptr = other_shared_ptr.raw_ptr;
        other_shared_ptr.raw_ptr = nullptr;
        reference_count = other_shared_ptr.reference_count.load();
        other_shared_ptr.reference_count = nullptr;
        
        deleter = other_shared_ptr.deleter;        
    }
    
    Shared_Ptr& operator=(Shared_Ptr&& other_shared_ptr)
    {
        // transfer the ownership of memory 
        raw_ptr = other_shared_ptr.raw_ptr;
        other_shared_ptr.raw_ptr = nullptr;
        reference_count = other_shared_ptr.reference_count.load();
        other_shared_ptr.reference_count = nullptr;
        
        deleter = other_shared_ptr.deleter;
        
        return *this;
    }
    
    // define basic operations supported by a regular pointer
    // 1. dereference operation
    T& operator*() const 
    {
        return *raw_ptr;
    }
    
    // 2. member selection operation
    T* operator->() const 
    {
        return raw_ptr;
    }
    
    // 3. indexing operation ( ONLY for array version ) 
    /*T& operator[](const int index)
    {
        return raw_ptr[index];
    }*/
    
    // 4. equality check 
    bool operator==(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr == other_shared_ptr.raw_ptr);
    }
    
    // 5. in-equality check 
    bool operator!=(const Shared_Ptr& other_shared_ptr) const 
    {
        return!(this->operator==(other_shared_ptr));
    }
    
    // 6. less than 
    bool operator<(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr < other_shared_ptr.raw_ptr);
    }
    
    // 7. greater than 
    bool operator>(const Shared_Ptr& other_shared_ptr) const 
    {
        return!(this->operator<(other_shared_ptr));
    }    
    
    // 8. less than or equal  
    bool operator<=(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr <= other_shared_ptr.raw_ptr);
    }
    
    // 9. greater than or equal 
    bool operator>=(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr >= other_shared_ptr.raw_ptr);
    }    
    
    T* get() const 
    {
        return raw_ptr;
    }
    
    explicit operator bool() const 
    {
        return (raw_ptr != nullptr);
    }
    
    T* release()
    {
        T* temp = raw_ptr;
        raw_ptr = nullptr;
        reference_count = nullptr;
        
        return temp;
    }
    
    void reset(T* new_ptr)
    {
        T* old_ptr =  raw_ptr;
        raw_ptr = new_ptr;
        reference_count = 1; // reset back to 1
        
        if(old_ptr != nullptr)
        {
            deleter(old_ptr); 
        }
    }
    
    int use_count() const 
    {
        return *reference_count;
    }
    
};

// Array version T[] with custom deleter support 
template< typename T, typename TP > // Here TP already has the default type as default_deleter<T>
class Shared_Ptr<T[], TP> // Must have Shared_Ptr<T> already defined for T[] to work 
{
private:
    std::atomic<int*> reference_count;
    T * raw_ptr; // pointer to an array of T's
    TP deleter;
public:
    Shared_Ptr(T *object) : 
        raw_ptr{object}, 
        deleter{default_deleter<T[]>()}, // Here we copy-construct specialized deleter<T[]>
        reference_count(new int(1)) // cannot use {}, use ()
    {
        cout << "Shared_Ptr [] created with Ref count : " << *reference_count << endl;
    }
    
    Shared_Ptr(T* object, TP this_deleter): 
        raw_ptr{object}, deleter{this_deleter}, 
        reference_count(new int(1)) // cannot use {}, use ()
    {
        cout << "Shared_Ptr [] created with Ref count : " << *reference_count << endl;
    }
    
    ~Shared_Ptr()
    {
        if(reference_count != nullptr)
        {
            --(*reference_count);
            cout << "Shared_Ptr [] destructor Ref count : " << *reference_count << endl;
            if(*reference_count == 0)
            {
                if(raw_ptr != nullptr)
                {
                    deleter(raw_ptr);
                }
            }
        }
    }
    
    TP& get_deleter()
    {
        return deleter;
    }
    
    // define copy operations
    Shared_Ptr(const Shared_Ptr& other_shared_ptr)
    {
        reference_count = other_shared_ptr.reference_count.load();
        raw_ptr = other_shared_ptr.raw_ptr;
        
        if(raw_ptr != nullptr)
        {
            ++(*reference_count);
        }
        
        deleter = other_shared_ptr.deleter;
        
        cout << "In Shared_Ptr [] Copy constructor Ref count : " << *reference_count << endl;
        
    }
    
    Shared_Ptr& operator=(const Shared_Ptr& other_shared_ptr)
    {
        reference_count = other_shared_ptr.reference_count.load();
        raw_ptr = other_shared_ptr.raw_ptr;
        
        if(raw_ptr != nullptr)
        {
            ++(*reference_count);
        }
        
        deleter = other_shared_ptr.deleter;
        
        cout << "In Shared_Ptr [] Copy =operator Ref count : " << *reference_count << endl;
        
        return *this;
    }
    
    // Define move operations
    Shared_Ptr(Shared_Ptr&& other_shared_ptr)
    {
        // transfer the ownership of memory 
        raw_ptr = other_shared_ptr.raw_ptr;
        other_shared_ptr.raw_ptr = nullptr;
        
        deleter = other_shared_ptr.deleter; 
        
        reference_count = other_shared_ptr.reference_count.load();
        other_shared_ptr.reference_count = nullptr;
        
    }
    
    Shared_Ptr& operator=(Shared_Ptr&& other_shared_ptr)
    {
        // transfer the ownership of memory 
        raw_ptr = other_shared_ptr.raw_ptr;
        other_shared_ptr.raw_ptr = nullptr;
        
        deleter = other_shared_ptr.deleter; 
        
        reference_count = other_shared_ptr.reference_count.load();
        other_shared_ptr.reference_count = nullptr;
        
        return *this;
    }
    
    // define basic operations supported by a regular pointer
    // 1. dereference operation
    T& operator*() const 
    {
        return *raw_ptr;
    }
    
    // 2. member selection operation
    T* operator->() const 
    {
        return raw_ptr;
    }
    
    // 3. indexing operation ( ONLY for array version ) 
    T& operator[](const int index)
    {
        return raw_ptr[index];
    }
    
    // 4. equality check 
    bool operator==(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr == other_shared_ptr.raw_ptr);
    }
    
    // 5. in-equality check 
    bool operator!=(const Shared_Ptr& other_shared_ptr) const 
    {
        return!(this->operator==(other_shared_ptr));
    }
    
    // 6. less than 
    bool operator<(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr < other_shared_ptr.raw_ptr);
    }
    
    // 7. greater than 
    bool operator>(const Shared_Ptr& other_shared_ptr) const 
    {
        return!(this->operator<(other_shared_ptr));
    }    
    
    // 8. less than or equal  
    bool operator<=(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr <= other_shared_ptr.raw_ptr);
    }
    
    // 9. greater than or equal 
    bool operator>=(const Shared_Ptr& other_shared_ptr) const 
    {
        return(raw_ptr >= other_shared_ptr.raw_ptr);
    }    
    
    T* get() const 
    {
        return raw_ptr;
    }
    
    explicit operator bool() const 
    {
        return (raw_ptr != nullptr);
    }
    
    T* release()
    {
        T* temp = raw_ptr;
        raw_ptr = nullptr;
        reference_count = nullptr;
        
        return temp;
    }
    
    void reset(T* new_ptr)
    {
        T* old_ptr =  raw_ptr;
        raw_ptr = new_ptr;
        reference_count = 1; // reset back to 1
        
        if(old_ptr != nullptr)
        {
            deleter(old_ptr);
        }
    }
    
    int use_count() const 
    {
        return *reference_count;
    }
    
};

// A custom deleter 
struct Custom_Deleter
{
    void operator()(int* ptr)
    {
        if(ptr != nullptr)
        {
            cout << "Custom deleter" << endl;
            // do some other cleanup if any
            delete ptr;
        }
    }
};

// A generic template based custom deleter 
template<typename G> // G for generic :) (kidding)
struct Generic_Custom_Deleter
{
private:
    // NOTE: The count_ is just used to identify the 
    // Generic_Custom_Deleter that is called 
    // when a user changes the deleter after 
    // the Shared_Ptr has been already created
    int count_;
public:
    Generic_Custom_Deleter(int count = 0): count_{count} {}
    void operator()(G* ptr)
    {
        if(ptr != nullptr)
        {
            cout << "Generic Custom deleter - " << count_ << endl;
            // do some other cleanup if any
            delete ptr;
        }
    }
};

// A function type deleter 
void deleter_function(int* ptr)
{
    if(ptr != nullptr)
    {
        cout << "Function deleter" << endl;
        // do some other cleanup if any
        delete ptr;
    }
    
    return;
}

struct Custom_Array_Deleter
{
    void operator()(int *ptr)
    {
        if(ptr != nullptr)
        {
            cout << "Custom_Array_Deleter" << endl;
            delete[] ptr; // see the array version of delete[] used here 
        }
        
        return;
    }
};

int main()
{   
    {
        Shared_Ptr<int> sh_ptr1(new int); 
        // local scope 1
        {
            Shared_Ptr<int> sh_ptr2 = sh_ptr1; // copy construction 
            *sh_ptr2 = 5;
        }
        
        cout << "Outside local scope 1" << endl;
        cout << "*shptr1 : " << *sh_ptr1 << endl;
    
    }
    
    cout << endl;
    
    {
        const int size = 10;
        Shared_Ptr<int[]> sh_ptr3(new int[size]); 
        // local scope 2
        {
            Shared_Ptr<int[]> sh_ptr4 = sh_ptr3; // copy construction 
            for(int index = 0; index < size; ++index)
            {
                sh_ptr4[index] = index*10;
            }
        }
        
        cout << "Outside local scope 2" << endl;
        
        for(int index = 0; index < size; ++index)
        {
            cout << "sh_ptr3[" << index << "] : " << sh_ptr3[index] << endl;
        }
    }
    
    return 0;
}

I will explain later why we have to use normal parantheses () instead of curly braces {}, way of construction for atomic reference count, also, why to use load () while copying atomic variables. For now, just focus on the working of shared pointers.

Let us see how reference count actually tracks the shared ownership. I have purposefully defined local scopes in the main() to show how reference count is checked by the Shared_Ptr’s destructor before deleting the pointer and releasing the memory.

Let us see the result now:

Shared_Ptr created with Ref count : 1
In Shared_Ptr Copy Constructor Ref count : 2
In Shared_Ptr Destructor Ref count : 1
Outside local scope 1
*shptr1 : 5
In Shared_Ptr Destructor Ref count : 0
default_deleter
Shared_Ptr [] created with Ref count : 1
In Shared_Ptr [] Copy constructor Ref count : 2
Shared_Ptr [] destructor Ref count : 1
Outside local scope 2
sh_ptr3[0] : 0
sh_ptr3[1] : 10
sh_ptr3[2] : 20
sh_ptr3[3] : 30
sh_ptr3[4] : 40
sh_ptr3[5] : 50
sh_ptr3[6] : 60
sh_ptr3[7] : 70
sh_ptr3[8] : 80
sh_ptr3[9] : 90
Shared_Ptr [] destructor Ref count : 0
default_deleter []

Try to track the reference count of shared Shared_Ptr instances and see when the actual delete is getting called.

The thread safety of shared pointers are to be discussed further. The standard only guarantees atomic operations on the reference count of the shared pointer and not on the object itself that shared pointer points to. I have only made the reference count as atomic here.

Enjoyed the chapter? Let me know in the comments below. Thanks! 🙂

2 thoughts on “Chapter 10 : Shared Pointers, An Introduction To Atomics In C++

  1. There are many bugs in your shared_ptr implementation. Starting with the simplest

    Shared_Ptr ptr{nullptr};

    Why do you want ref_count even with the value of 1 should exist? Ideally it shouldn’t.

    Additionally your content requires more than 50% width of screen but you allocated approx 30% of screen width. It gives pain.

    I don’t think, people love to watch all the code at once but relevant part at once.

Leave a Reply