Open this wandbox
(b, b, b,
b, b,
b). It contains an almost-complete implementation of
shared_ptr
.
1. Find the definition of increment_use_count
in "shared-ptr.h". Fill in the blanks according to the following algorithm:
m_ctrl
is null, don't do anything.m_ctrl->m_use_count
.
2. Find the definition of decrement_use_count
in "shared-ptr.h". Fill in the blanks according to the following algorithm:
m_ctrl
is null, don't do anything.m_ctrl->m_use_count
.m_use_count
just hit zero, then delete the controlled object.
(Don't just do delete m_ptr
! You need to ask the control block
how to delete the original controlled object.)m_use_count
just hit zero, then decrement m_weak_count
by 1.m_weak_count
hit zero, then free the control block
by calling delete m_ctrl
.
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--
!)
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.