Re: Virtual Ctor Idiom and auto_ptr
James Kanze wrote:
In the FAQ, the virtual constructor idioms, create() and clone(), use raw
pointer return values.
Wouldn't it be better if these returned auto_ptr's instead?
But then covariant return types can't be exploited.
Here's some sample code.
Note that the use of clone() in main() is difficult to upcast.
I suppose that if one is using clone() then polymorphic behavior is
probably
desired, so the upcast typically isn't necessary.
I forgot to mention this in my first answer, but clone() and
create() typically have a very strict post condition, which must
be met by all derived classes, and so are almost never virtual,
but rather call a private virtual function to do the work, and
then verify the post-condition, i.e.:
Base*
Base::clone() const
{
Base* result = doClone() ;
assert ( typeid( *result ) == typeid( *this ) ) ;
return result ;
}
I did do that, but mine returned auto_ptr<Base> instead.
So covariant return types don't apply anyway.
And of course, if a derived class did want to provide a clone()
which returned a Derived*, it is free to do so. Most of the
time, of course, there's no point in it, but I suppose there are
exceptions, e.g. if the derived class defines some sort of
extended contract.
Yes, that's better. Derived can "override" create() and clone() without
any
adverse affects.
public:
std::auto_ptr<Derived> create() const { return
std::auto_ptr<Derived>(doCreate()); }
std::auto_ptr<Derived> clone() const { return
std::auto_ptr<Derived>(doClone()); }
I'm still stuck on the "rule" that one must not override a non-virtual
member function.
I spent a day writing a clone_ptr<T> class template, returned instead of an
auto_ptr<T> above.
The copy operation would clone() instead of passing ownership along.
I'm sure I'm not the first with this idea, and since this technique isn't
prevalent, I put it in the e-trash.
Does anyone think a clone_ptr<T> is practical?
terry
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]