Consider the following code snippet taken from Herb Sutter\'s talk on atomics:
The smart_ptr class contains a pimpl object called control_block_ptr containing the refere
Boost.Atomic library that emulates std::atomic provides similar reference counting example and explanation, and it may help your understanding.
Increasing the reference counter can always be done with
memory_order_relaxed: New references to an object can only be formed from an existing reference, and passing an existing reference from one thread to another must already provide any required synchronization.It is important to enforce any possible access to the object in one thread (through an existing reference) to happen before deleting the object in a different thread. This is achieved by a "release" operation after dropping a reference (any access to the object through this reference must obviously happened before), and an "acquire" operation before deleting the object.
It would be possible to use
memory_order_acq_relfor the fetch_sub operation, but this results in unneeded "acquire" operations when the reference counter does not yet reach zero and may impose a performance penalty.