Date: Thu, 13 Feb 2025 19:37:49 +0000
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. Not having it leaves us using raw pointers and we don't have a good art of preventing them from dangling (knowing if they are still valid). Our mitigations tend to be fragile and often break. It is scary enough to deter us from doing such a thing but sometimes we have to and it is here that dangling pointers remain a huge hazard.
It doesn't have to be like that, We can have a smart pointer for the role but it will be involve intrusion on the owning unique_ptr declaration so it can notify deletes and some reference counting overhead but with that it is rock solid (valid or null). Here is a working example:
https://github.com/make-cpp-nice/ptr_to_unique A smart pointer to an object already owned by a unique_ptr. It doesn't own the object but it self zeroes when the object is deleted so that it can never dangle.
The addition of something like this to the Standard Library would complete safe smart pointer coverage for heap allocated objects. It is the missing piece needed to do this. Its safe encapsulation of an idiom that was unreasonably hazardous will also open up new design opportunities.
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. Not having it leaves us using raw pointers and we don't have a good art of preventing them from dangling (knowing if they are still valid). Our mitigations tend to be fragile and often break. It is scary enough to deter us from doing such a thing but sometimes we have to and it is here that dangling pointers remain a huge hazard.
It doesn't have to be like that, We can have a smart pointer for the role but it will be involve intrusion on the owning unique_ptr declaration so it can notify deletes and some reference counting overhead but with that it is rock solid (valid or null). Here is a working example:
https://github.com/make-cpp-nice/ptr_to_unique A smart pointer to an object already owned by a unique_ptr. It doesn't own the object but it self zeroes when the object is deleted so that it can never dangle.
The addition of something like this to the Standard Library would complete safe smart pointer coverage for heap allocated objects. It is the missing piece needed to do this. Its safe encapsulation of an idiom that was unreasonably hazardous will also open up new design opportunities.
Received on 2025-02-13 19:37:52