Subject: [boost] [SmartPointers] Determine interest in a new pointer wrapper class "flex_ptr"
From: Jakob Riedle (jakob.riedle_at_[hidden])
Date: 2015-03-22 18:04:56
Hello Boost Community,
In the last few weeks, I heavily felt the lack of boost not having a more lightweight solution to a "not-necessarily-owning" pointer-wrapper than shared_ptr.
shared_ptr is quite slow in the context that I need it to work.
Furthermore it always is owning, even though ownership is shared in between instances.
This is unhelpful, if you have an std::list of both non-owning and owning pointers.
Hence, if you do not want to use shared_ptr all over your project, or especially want to interact with C, you need a not-necessarily-owning pointer-wrapper.
This is why I collected some ideas on how to improve the situation.
I came up with a little class named 'flex_ptr', that can hold both strong and weak references (therefore the name 'flexible', but it can also be 'the name of whatever proves itself to be good ...').
It keeps track of whether the held pointer is strong or weak.
The Class doesn't need reference counting, since an Instance either is owning, or non-owning.
Ownership is transferred between Instances using the default Move/Copy behavior.
By Default the Constructor takes a pointer and treats it as a weak one.
This is required, since this class aims on being used only at places, that are ought to be able to but not necessarily own objects. (Excuse me for the long sentence) A flex_ptr instance holding a strong pointer is created using a static non-member method named 'make_owning_flex', which accepts an rvalue pointer.
As a result, it is not required to use the class at every single pointer occurrences in the project, but only at places, where the programmer wants to allow but not force strong references.
The flex_ptr class is easily integrated into existing code using unique_ and shared_ptr's: One could think of
- a constructor accepting a const lvalue reference unique_ptr, creating a (flex_ptr-instance holding a) weak reference,
- a constructor accepting an rvalue unique_ptr, creating a strong pointer, that is owning an object it received from unique_ptr,
- as well as a constructor taking a const lvalue reference shared_ptr, creating a weak pointer.
This pattern allows outright memory management, it uses less memory than shared_ptr (because no reference counting object required), therefore is faster, allows well-defined interactions similar to unique_ptr (especially at interaction with C) and thus fills a yet unclosed gap in the boost library as well as the Standard.
Since this is (only) my personal opinion, I'd like to see how people feel about this 'gap'
and think about this addition in the library (however the pattern may be implemented in the end).
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk