C++ Logo


Advanced search

Re: [std-proposals] std::shared_ptr resurrect

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Mon, 11 Dec 2023 17:43:40 +0300
On 12/11/23 15:00, Valentin Palade via Std-Proposals wrote:
> Hello Everyone,
> I would like your opinion on a small addition to the std::shared_ptr:
> bool std::shared_ptr::resurrect();
> with the following behavior:
> * will atomically decrement the use counter and
> o if use counter != 0 will reset the shared_ptr instance and
> return false
> o otherwise, increment the use counter, leave the shared_ptr
> instance unchanged and return true (thus resurrecting the
> shared_ptr instance).
> Usage scenario:
> * producer creates a shared_ptr message to be sent to multiple
> consumers - threads/actors/connections
> * on consumers, we want to be able to return the shared_ptr message to
> the producer (e.g. to be reused), once consumed by all.

Why can't you use use_count()? If it returns 1, your shared_ptr is the
last instance and you may reuse it, as if your proposed resurrect()
returned true.

Note that this is thread safe since use_count() == 1 means there are no
other threads that may concurrently modify the reference counter.

Received on 2023-12-11 14:43:43