Re: How to implement the virtual constructor behavour in C++
Mathias Gaunard <loufo...@gmail.com> wrote:
<Roman.Perepeli...@gmail.com> wrote:
1. Cloning.
struct Shape
{
virtual Shape * Clone() const = 0;
};
template <class Derived, class Base>
struct CloneImpl : Base
{
virtual Derived * Clone() const
{
return new Derived(static_cast<const Derived &>(*this));
}
You're combining the allocation strategy and the virtual copy
constructor.
I believe the way memory should be allocated should be for the user to
decide and not embedded in the object definition.
Good point! I didn't realize in the first place why did you use
placement new for cloning. Now I see it. And on the top of your
interface it is possible to implement convenient clone function:
Shape * Clone(Shape * s)
{
void * res = operator new(s->Size());
try {
s->Clone(res);
return static_cast<Shape*>(res);
} catch (...) {
operator delete(res);
throw;
}
}
I believe it is portable to call 'delete' on the result of
this Clone function because Shape does not specify overloaded
operator delete. Is it correct?
Circle c;
delete Clone(&c); // is it standard conforming?
Roman Perepelitsa.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]