About cloning
Cloning an object, meaning copying it polymorphically, is usually done
this way:
class Base
{
virtual Base* clone() const = 0;
}
class Derived : public Base
{
Base* clone() const
{
return new Derived(*this);
}
};
However, this requires usage of new. An user may not want to use new to
allocate the new copied object.
Especially if that user already knows he has enough memory to store it
somewhere else.
The standard way to customize that seems to be allocators.
I have rather little knowledge of them so I may not be using them the
right way.
Of course we can only pass an allocator for the base type, since the
only one who knows about the actual derived type is the virtual member
function, which will then rebind the allocator.
(let's imagine template virtuals exist -- the fact that they don't is
another problem to solve though, one possibility would be to make every
class a template or to put the clone member in another templated class
that we reference, which would require an extra pointer in every
instance of our class)
class Base
{
template<typename Allocator = std::allocator<Base> >
virtual Base* clone(const Allocator& alloc = Allocator()) const = 0;
};
class Derived : public Base
{
template<typename Allocator = std::allocator<Base> >
Base* clone(const Allocator& alloc = Allocator()) const
{
return new(((typename Allocator::template
rebind<Derived>::other)(alloc)).allocate(1)) Derived(*this);
}
};
Ok so now we can clone our object rather flawlessly.
How do we deallocate the memory though? The allocator interface needs to
know the actual type to deallocate (unlike new/delete which stores by
himself the size of the type somewhere), so we have to add an extra
virtual member function.
That basically makes it redundant with a virtual destructor, which is
actually quite useless, since only useful with delete.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]