> I have checked the code and both versions seem to work fine.
They do, but the reference version is not natural. You're not supposed
to take the address of a reference and call delete on it. A pointer
implies that the object probably needs to be deleted at one moment. You
can't say the same of references.
> Ultimately I want to use this
> code concept in a class to offer Clone() functionality.
Make Clone a virtual member function of the class, and make it call the
copy constructor:
sturct Base
{
virtual ~Base();
virtual Base* Clone() const = 0;
};
struct D1 : public Base
{
D1();
D1(const D1&);
virtual D1* Clone() const { return new D1(*this); }
};
struct D2 : public Base
{
D2();
D2(const D2&);
virtual D2* Clone() const { return new D2(*this); }
};
I strongly recommend that you consider using boost::shared_ptr and
forget about about native pointers. Not only will you avoid most memory
leaks that way, but you can also say goodbye to double deletion and
pointers to rogue objects (invalid objects, already deleted objects).
Using weak_ptr, you can make sure that when an object dies, all pointers
to that object get automatically NULLed out. IMO, it's the single most
important library feature that radically improves your code quality.
I wrote a small introductory tutorial about shared_ptr:
http://tweakbits.com/articles/sharedptr/index.html
Tom
Abubakar - 24 Apr 2006 10:45 GMT
Thanks for the code.
Ab.
> > I have checked the code and both versions seem to work fine.
>
[quoted text clipped - 41 lines]
>
> Tom