suggestion: harness destructor in scoped_ptr<>::reset
Before I propose this to main boost mailing list, I wanted to see what others thought of this idea. I propose changing the following method on scoped_ptr<>: void reset(T* p=0) {if(ptr!=p) {checked_delete(ptr); ptr=p;}} to void reset(T* p=0) {if(ptr!=p) {scoped_ptr<T>(p).swap(*this);}} void swap(scoped_ptr<T>& other) {std::swap(ptr,other.ptr);} Of course, we would then have global methods for std::swap, as there are for the other smart pointers, to map to this method. Finally, the same change should be made to scoped_array<>. shared_ptr<> and shared_array<> already have these semantics. The idea is to harness the destructor of the scoped_ptr in order to delete the pointer, rather than calling checked_delete in two places. This has a few advantages over the old code: 1- destruction is handled in one place, the destructor. This seems natural, and gives developers one place to look to see what happens when a pointer is deleted 2- I have had occasion to specialize the destructor of the scoped_ptr<> class to do something other than delete. In that case, I needed to specialize the destructor AND the reset method. With this change, one would only need to specialize the destructor and reset would harness that specialization as well. Comments?
At 4:36 PM +0000 4/2/02, jlehrer wrote:
Before I propose this to main boost mailing list, I wanted to see what others thought of this idea.
I propose changing the following method on scoped_ptr<>:
void reset(T* p=0) {if(ptr!=p) {checked_delete(ptr); ptr=p;}}
to
void reset(T* p=0) {if(ptr!=p) {scoped_ptr<T>(p).swap(*this);}} void swap(scoped_ptr<T>& other) {std::swap(ptr,other.ptr);}
Of course, we would then have global methods for std::swap, as there are for the other smart pointers, to map to this method.
Finally, the same change should be made to scoped_array<>. shared_ptr<> and shared_array<> already have these semantics.
The idea is to harness the destructor of the scoped_ptr in order to delete the pointer, rather than calling checked_delete in two places.
This has a few advantages over the old code:
1- destruction is handled in one place, the destructor. This seems natural, and gives developers one place to look to see what happens when a pointer is deleted
2- I have had occasion to specialize the destructor of the scoped_ptr<> class to do something other than delete. In that case, I needed to specialize the destructor AND the reset method. With this change, one would only need to specialize the destructor and reset would harness that specialization as well.
Comments?
Sound OK to me. While I don't think this is off topic for this, I don't see any reason not to post it directly to developers list. This is, after all, a question about improving the implementation. -- Jon Kalb Kalb@LibertySoft.com
participants (2)
-
jlehrer
-
Jon Kalb