C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Mon, 24 Feb 2025 20:20:00 -0300
On Monday, 24 February 2025 17:21:43 Brasilia Standard Time Ell via Std-
Proposals wrote:
> If we don't care about thread safety,
> the ptrs_to_unique could form an (intrusive) linked list, and get
> individually cleared when the object gets destroyed. This does make
> destruction more expensive, but it has the benefit of not requiring a
> separate dynamic allocation, which makes the construction of
> ptr_to_unique noexcept. It also makes the actual use of the pointer
> comparable to using a raw pointer, instead of having to validate the
> pointer against the control block first.

The destruction must be more expensive because there's non-zero amount of
extra work to happen. There's no escaping that.

I think I understand this linked list solution. The observable_ptr class
contains two pointers: one to the object and one to the list, initially set to
null. Each ptr_to_unique that gets added simply inserts into the head of the
list, so it's noexcept and O(1). Removal from the list requires finding the
item, so it's O(n). Destruction of the object must iterate through all
entries, so it's also O(n).

I would much rather have the observable_ptr class allocate the extra block and
add a ref-count. The creation of the object is usually already not noexcept,
so it wouldn't be adding an extra requirement. However, all the operations
above are O(1). And as a bonus, it's also thread-safe.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel DCAI Platform & System Engineering

Received on 2025-02-24 23:20:05