Exercise 5. Smart pointers from scratch.

Open this wandbox (b, b, b, b, b, b). It contains an almost-complete implementation of shared_ptr.

Exercise 5a. Atomic reference-counting

1. Find the definition of increment_use_count in "shared-ptr.h". Fill in the blanks according to the following algorithm:

2. Find the definition of decrement_use_count in "shared-ptr.h". Fill in the blanks according to the following algorithm:

Run the test cases in "test-refcounting.cc". They should pass.

3. Use the -DX=std::this_thread::sleep_for(1ms); trick that we learned in Exercise 4 to stress-test your increment_use_count and decrement_use_count code. Does it still work? (It should.) If X exposes bugs in your code, try to fix them. Pay attention to "time-of-check-to-time-of-use" races: you must not allow any time to elapse between decrementing m_use_count and fetching its new value. (Use the return value of operator--!)

Exercise 5b (optional). Metaprogramming enable_shared_from_this

1. (Optional) Study the code in this exercise's wandbox. It includes an almost-complete implementation of enable_shared_from_this. Can you see how to connect maybe_enable_sharing_from_this to the definition of enable_shared_from_this from Arthur's from-scratch repo?

2. (Optional) Try to understand the SFINAE on maybe_enable_shared_from_this. The file "test-crtp.cc" (backup) may be helpful to understand the corner cases.


You're done with this set of exercises! Sit back and relax, or optionally, study the code in this exercise's wandbox.