|
Boost : |
From: John Maddock (John_Maddock_at_[hidden])
Date: 2001-12-28 07:51:01
At the risk of muddying the waters still further, I have a version of
scoped_ptr which:
* doesn't change the implementation at all for existing compilers
* fixes the premature destructor instantiation problem with bcb5, without
increasing the size of the object (by using a static callback pointer).
Really this is just a modified version of Fernando's grinning_pointer.
On the down side:
* for non-Borland users this introduces a gatuitous dependency change in
smart_ptr.
* introduces a subtle difference in behaviour between Borland and
non-Borland compilers.
Anyway here is the code:
template<typename T> class scoped_ptr : noncopyable {
T* ptr;
#ifdef __BORLANDC__
static void (*s_callback)(T*);
#endif
public:
typedef T element_type;
explicit scoped_ptr( T* p=0 ) : ptr(p)
{
#ifdef __BORLANDC__
if(0 == s_callback) s_callback = &checked_delete<T>;
#endif
} // never throws
~scoped_ptr()
{
#ifndef __BORLANDC__
checked_delete(ptr);
#else
//assert(s_callback);
s_callback(ptr);
#endif
}
void reset( T* p=0 ) { if ( ptr != p ) { checked_delete(ptr);
ptr = p; } }
T& operator*() const { return *ptr; } // never throws
T* operator->() const { return ptr; } // never throws
T* get() const { return ptr; } // never throws
#ifdef BOOST_SMART_PTR_CONVERSION
// get() is safer! Define BOOST_SMART_PTR_CONVERSION at your own risk!
operator T*() const { return ptr; } // never throws
#endif
}; // scoped_ptr
#ifdef __BORLANDC__
template <class T>
void (*scoped_ptr<T>::s_callback)(T*);
#endif
BTW the btl tests all compile OK with this version of scoped_ptr (excluding
unit_test_suite_ex_test.cpp whcih still seems to have problems with bind
usage).
- John Maddock
http://ourworld.compuserve.com/homepages/john_maddock/
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk