Re: Virtual Ctor Idiom and auto_ptr
Terry G ha scritto:
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.
Yes, that's unfortunate but inevitable, I'm afraid. However, you can
mimic covariant types with templates. Instead of defining create() and
clone() as function members, define them as free function templates:
template <class T>
std::auto_ptr<T> clone(const T& x)
{
return std::auto_ptr<T>(x.doClone());
}
You can add a test "assert(typeid(*ptr) == typeid(x));" if you want.
The only problem is that you have to find a way to provide clone() with
access to the private member doClone(). A friend declaration might
suffice, but it's long and ugly to write. One nice way I see used in the
boost.serialization library is the following. Modify the code above to:
class clonable_access
{
// add create() here
template <class T>
friend std::auto_ptr<T> clone(const T& x);
template <class T>
inline static T* doClone(const T& x) { return x.doClone(); }
};
template <class T>
inline std::auto_ptr<T> clone(const T& x)
{
return std::auto_ptr<T>(clonable_access::doClone(x));
}
then a mere "friend class clonable_access;" will be enough.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]