From: Mathias Gaunard (mathias.gaunard_at_[hidden])
Date: 2007-09-21 12:25:37


Igor.Smirnov_at_[hidden] wrote:

> May be I am behind progress, but I do not know a way to make cloning
> pointer (or that Mathias' value object, but this seems to be the same in
> principle) to be non-intrusive. You anyway need virtual cloning function
> in each class of the hierarchy.

Boost.Any, for example, copies dynamically objects without having to
modify their type.

Here is a simplistic possible implementation for our case.

template<typename T, typename D>
T* clone_function(const T& t)
{
     return new D(static_cast<const D&>(t));
}

template<typename T>
class Container
{
     template<typename D>
     Container(const D& d) : obj(new D(d)), clone(clone_function<T, D>)
     {
     }

     // copy constructor, operator=, etc.

     ~Container()
     {
        delete obj;
     }

     T* obj;
     T* (*clone)(const T&);
};

As I said earlier, this has a few flaws:
- one word per object is wasted. Polymorphic objects already have one
word that identifies their type (the pointer to the vtable)
- it assumes that the static type of the object the container acquires
is the same as its dynamic type.