C++ Logo

std-proposals

Advanced search

Re: [std-proposals] A non-owning but self zeroing smart pointer for single ownership

From: Simon Cooke <sicooke_at_[hidden]>
Date: Sun, 16 Feb 2025 12:33:03 -0500
On Sat, Feb 15, 2025, 01:21 Simon Schröder via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> As others have mentioned shared_ptr + weak_ptr almost do what you want.
> What’s missing is a unique_shared_ptr which would use the implementation of
> shared_ptr, but would only allow for a single owner (i.e. only move is
> allowed, but no copy). In the long run such a type could easily be
> implemented using reflection (by wrapping shared_ptr and forwarding
> (almost) all function calls to it).
>

If we look at the intended usage, the pattern that gets us there is an
object that owns a private shared_ptr, but only hands out weak_ptrs from
its API surface.

Clients of the object have zero long term control over the shared pointer's
lifetime, beyond preventing destruction of the object for the duration of
the time they've taken a reference.

In the event that another object needs to participate in ownership of the
object, it could use a different method to get a strong reference.

This isn't an arbitrary or opaque architectural design choice though - so
it seems like something best handled by design policy, rather than code,
IMO.

Simon

Received on 2025-02-17 00:18:28