Re: Generic clone
Hi,
Mathias Gaunard wrote:
> On Aug 21, 5:27 am, Simon Richter <Simon.Rich...@hogyros.de> wrote:
>> occasionally, I have wished for a way to create a copy of a
>> polymorphic object that I do not know the dynamic type of, i.e. the
>> infamous clone() method.
> Your clone function is responsible for allocating your memory. That's
> where the root of the ugliness lies. A virtual constructor should just
> be a way to construct, not be a way to allocate memory, construct, and
> then return a pointer to that memory that will be handled by who knows
> who.
Indeed, however it cannot be properly done using the standard
allocators; this would require virtual methods with "free" template
parameters (for the allocator), which cannot be done. If you are using
clone(), you have left the realm of allocators anyway, as you need to
destruct your objects with delete then, and only overriding operator
delete will help here.
The language extension I proposed in my original posting can be used to
retrieve size and alignment requirements; allocation will have to happen
through operator new anyway, though.
> Plus not everyone may want to use new to allocate your object, because
> they need to allocate it in a special place or because they need to
> allocate it in a special pool. (think embedded systems, kernel
> programming, etc.)
Being an embedded systems programmer, I'm usually the first to jump into
peoples' faces for not using allocators; in this particular instance, it
is not possible, however, since the allocator needs to know the type of
object instantiated statically.
> template<typename T>
> T* new_clone(const T& t)
> {
> T* tmp = ::operator new(t.size_and_align().first);
No. This goes around the type-specific operator new, so deleting the
object would invoke UB.
terminator(jam) wrote:
generic_wrapper(Data *ptr): me(ptr){
if( typeid(Data)!=typeid(*ptr) ) throw
bad_cast;
};
This at least makes the slicing condition runtime detectable, which is a
certain improvement.
void* my_clone=aw.clone();//destroy with dispose
....//etc
This means that I will have to carry around the pointer to the abstract
wrapper along with the pointer to the object itself?
Simon
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]