First of all: I really hate plain pointers so I am probably biased when it
comes to judge the benefits of implementations using pointers. 

The problem is, we currently need pointers in order to use virtual
functions (references are not acceptable, since we can't put them in
containers for instance...).

The following proof-of-concept code shows that we can have the pie and eat
it, i.e. to have value-semantics _and virtual functions:

--------------------------------- snip -------------------------------
#include <iostream>
#include <vector>

using namespace std;


struct base
{
        virtual void print() const
                { cout << "base\n"; }

        virtual base * clone() const
                { return new base; }
};


struct derived1 : public base
{
        void print() const
                { cout << "derived1\n"; }

        derived1 * clone() const
                { return new derived1; }
};


struct derived2 : public base
{
        void print() const
                { cout << "derived2\n"; }

        derived2 * clone() const
                { return new derived2; }
};

// wrapper around a pointer
struct item
{
        base * data_;

        template <class T> item(const T & t)
                        : data_(new T(t))
                { }

        item(const item & t)
                        : data_(t.data_->clone())
                { }

        void operator=(const item & t)
                {       delete data_;
                        data_ = t.data_->clone(); }

        ~item()
                { delete data_; }

        void print() const
                { data_->print(); }
};

int main()
{
        vector<item> v;
        derived1 d1;
        derived2 d2;

        v.push_back(d1);
        v.push_back(d2);
        v.push_back(d1);

        for (vector<item>::const_iterator it = v.begin(); it != v.end(); ++it)
                it->print();
        cout << endl;

        v[0] = v[1];

        for (vector<item>::const_iterator it = v.begin(); it != v.end(); ++it)
                it->print();
        cout << endl;

}
--------------------------------- snip -------------------------------

Result is:

derived1
derived2
derived1

derived2  
derived2
derived1

--------------------------------- snip -------------------------------

I think using this idiom we could save a lot of pain. Most classes that do
not have any pointer members do not need copy constructors, assigment
operators or destructors, so the mistakes are less likely... Not to mention
memory leaks...

I'd really like to try this at some time with MathParInset... 

Comments?

Andre'


-- 
André Pönitz ........................................ [EMAIL PROTECTED]

Reply via email to