C++ Logo

std-proposals

Advanced search

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

From: JOHN MORRISON <inglesflamenco_at_[hidden]>
Date: Mon, 17 Feb 2025 11:33:50 +0000
Simon Cooke wrote: 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.

Hi Simon,

This idea has been mentioned and discussed a few times. A special type of single ownership pointer that can be shared just for the duration of weak_ptr dereferences – a kind of unique_ptr with elastic destruction . The idea is that it would provide threadsafe references to singly owned objects from multiple threads and the required destruction delay will be so short that it won't be a problem.

To work it would require three new smart pointers:


  *
A new single ownership pointer that wraps a shared_ptr but presents a unique_ptr public interface.
  *
A new type of weak_ptr that can reference it and can only convert to the new type of shared_ptr mentioned below.
  *
A new type of shared_ptr that can only be constructed from the new type of weak_ptr and that cannot be copied, shared or converted to a normal shared_ptr.

I think that could be done with a bit of work. It sounds cool because it would allow what was never before possible and that we have always carefully avoided, singly owned objects being safely visible to multiple threads.

But is the idea fundamentally sound? Its magical bucking of the normal rules sounds too good to be true and that is because it isn't true. It still compromises single ownership. Even a short destruction delay can disrupt carefully crafted destruction sequences. It also overlooks the fact that we often use background threads to carry out lengthy tasks so we could be holding our supposedly singly owned object alive for quite some time. Lifetime elasticity is unwelcome in single ownership because it is all about being tight and timely.

This idea is an attempt to magically buck the reality that singly owned items should never be visible to multiple threads. This is a reality that we have always accepted and worked with and trying to pretend that it is otherwise is always going to be some kind of fragile illusion.

The proposed ptr_to_unique is designed to fully respect single ownership without compromising it in any way. It assumes that you will not be exposing your singly held object to multiple threads and you won't because you never did because it is not something you can ever do safely – you need shared ownership for that. If you use threads you will know that. If you don't use threads then it doesn't matter that you don't.

The following post has a lengthy rebuttal of the concerns about lack of thread safety with the proposed ptr_to_unique and I am trying to draw attention to it.

https://lists.isocpp.org/std-proposals/2025/02/12468.php




Received on 2025-02-17 11:33:53