Ernesto Bascón wrote:
I presume there are other functions omitted from your code above, and
from your description, it's not clear what semantics you are intending
to give this smart pointer (though it sounds like you want shared
ownership). Generally, smart pointers (e.g., std::auto_ptr,
std::tr1::share d_ptr, boost::scoped_p tr, Loki::SmartPtr, and the smart
pointer in FAQ 16.22) are responsible for cleaning up after themselves
at the appropriate time so that the user doesn't have worry about
deleting anything. Indeed, that's often the primary point. What is your
point?
Primarily, I want to provide a hierarchy of smart pointers, providing
the basic implementation in something like AbstractPtr<T>; the basic
implementation should include null pointer checking on -and dangling
pointer avoiding.
I want to provide also a Ptr<T: public AbstractPtr<Tim plementation
that should have the same behavior that the standard pointers, but with
the null pointer checking. This smart pointer should not have any
semantics (thus, should provide mechanisms to release the pointee
object manually).
Well, IMHO, its generally bad to have an explicit delete anywhere in
your main code. All resources are best managed by RAII and classes that
enable it (e.g., std::tr1::share d_ptr).
As for the hierarchy, I'm not quite sure why you're bothering. If
you're trying to create a variety of types of smart pointers, check out
Loki's policy-based solution.
As for a class that behaves just like a regular pointer but does
checking, how about something like:
template<class T>
class Ptr
{
T* p_;
public:
Ptr( T* const p=0 ) : p_(p) {}
operator T*() { assert( p_ ); return p_; }
T* operator->() { assert( p_ ); return p_; }
T& operator*() { assert( p_ ); return *p_; }
};
class C {};
Ptr<Cp1( new C );
delete p1;
If you had something grander in mind, I think you could achieve the
same thing (but with considerably more flexibility and code that is
already written and tested) with Loki's smart pointer by creating a
storage policy (let's call it NoDelete) identical to
Loki::DefaultSP Storage, except without the delete in its Destroy()
member function:
typedef Loki::SmartPtr< C,
Loki::NoCopy,
Loki::AllowConv ersion,
Loki::AssertChe ck,
NoDeleteMyPtr;
MyPtr p2( new C );
delete p2;
Hope that helps.
Cheers! --M