Ernesto Bascón wrote:
I am implementing my custom smart pointer:
template <typename T>
class MySmartPtr
{
public:
MySmartPtr(T* aPointer)
{
mPointer = aPointer;
}
inline T* operator->() const {return mPointer; }
private:
T* mPointer;
};
It could be used in this way:
MySmartPtr<Aobj = new A();
obj->Method1();
int value = obj->Method2();
The operator-overload allows accessing the A methods as they are
accessed via a common pointer.
I want to allow the final user call the delete operator as in a common
pointer when he wants to explicitly remove the pointer:
delete obj;
There is a way I could implement an overload of the delete pointer in
my MySmartPtr<Tor there is some workaround on this?
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?
As for overloading delete, you probably don't want to do that because
it would change the semantics of delete from operating on the object
(viz. MySmartPtr<>) to operating on the contained object. In other
words, class-specific new/delete operators are for deleting the smart
pointer class itself:
MySmartPtr<T>* pT
= new MySmartPtr<T>( 0 ); // Calls MySmartPtr<T>:: operator new
delete pT; // Calls MySmartPtr<T>:: operator delete
You could accomplish your goal by supplying a cast to T*, but that
allows some other dangerous code. The preferred method is to supply a
reset function:
template<class T>
void MySmartPtr<T>:: Reset( T* const p = 0 )
{
delete mPointer;
mPointer = p;
}
It's best to use RAII and let the smart pointer do the dirty work. See
the FAQ mentioned above and those following, and see this chapter from
_Modern C++ Design_ on Loki's smart pointers:
http://www.informit.com/articles/pri...p?p=25264&rl=1
Cheers! --M