Date: Fri, 14 Feb 2025 13:05:06 +0000
JOHN MORRISON wrote:
> A non-owning but self zeroing smart pointer for single ownership
> We need this when we want hold a persistent reference to an object already owned by a unique_ptr to use later if it is still valid.
> Here is a working example:
> https://github.com/make-cpp-nice/ptr_to_unique
I did something like this for the following scenario:
- A large data structure using unique_ptr, something like std::vector<
std::unique_ptr<T> >.
- Frequent writes, infrequent reads.
- Used from multiple threads, protected by a mutex.
- A small number of components that need to remember an element of the
data structure
for longer periods of time, and survive the case where the element is removed.
My "weak pointer for unique_ptr" uses a global table with approximately
one entry for
each weak pointer. Pointed-to objects need to inherit from a
WeakPointee base class,
but it adds no overhead to their size; IIRC all it does is add a
destructor. The unique_ptr
is not modified.
This seems to work well in practice, and in my case its low memory
overhead is a useful
feature, but it would not scale to larger numbers of weak pointers nor
to more frequent
writes. The github ptr_to_unique linked above takes a different
approach with different
tradeoffs.
As to whether something like this should be in the standard... I'm not convinced.
It works fine as a library feature.
(See also: Hazard Pointers?)
Regards, Phil.
> A non-owning but self zeroing smart pointer for single ownership
> We need this when we want hold a persistent reference to an object already owned by a unique_ptr to use later if it is still valid.
> Here is a working example:
> https://github.com/make-cpp-nice/ptr_to_unique
I did something like this for the following scenario:
- A large data structure using unique_ptr, something like std::vector<
std::unique_ptr<T> >.
- Frequent writes, infrequent reads.
- Used from multiple threads, protected by a mutex.
- A small number of components that need to remember an element of the
data structure
for longer periods of time, and survive the case where the element is removed.
My "weak pointer for unique_ptr" uses a global table with approximately
one entry for
each weak pointer. Pointed-to objects need to inherit from a
WeakPointee base class,
but it adds no overhead to their size; IIRC all it does is add a
destructor. The unique_ptr
is not modified.
This seems to work well in practice, and in my case its low memory
overhead is a useful
feature, but it would not scale to larger numbers of weak pointers nor
to more frequent
writes. The github ptr_to_unique linked above takes a different
approach with different
tradeoffs.
As to whether something like this should be in the standard... I'm not convinced.
It works fine as a library feature.
(See also: Hazard Pointers?)
Regards, Phil.
Received on 2025-02-14 13:05:08