Hello,
Scott Kilpatrick wrote:
Let's say I have a hacked-up polymorphic container that holds
variables of type:
struct poly {
union {
int *i;
double *d;
complex<double> *c;
} value;
char type;
};
Each time a value gets added to the container, it mallocs a new value,
It is "new", not "malloc", isn't it.
sets the type char, and sets the pointer to that new value. How, then,
do I write a destructor for poly? Do I do a switch on type and delete
value.x if it's that type? Also, how do you delete a poly if it
contains both pointers and non-pointers (non-pointers to native types
that is)?
There has to be a matching delete for every new you do. Anything else
will cause problems. You will have a hard time without switch on the
type field in the destructor.
But this is crude. Consider using OO techniques.
Introduce an abstract base class polybase, which will reduce poly to a
simple pointer. To be able to do this, replacing type fields by
inheritance, was one driving force behind the development of C++. In
terms of design pattern poly ends up as proxy class to the real poly,
which can be implemented in many ways.
A lot of sensible member functions and constructors are still missing.
class polybase
{
public:
virtual ~poly() = 0;
char type() = 0; // could be left out
// add appropriate interface
}
class intpoly: public polybase
{
char type() { return 'i';}
// implement interface
int i;
}
class doublepoly: public polybase
{
// implement interface
char type() { return 'd';}
double d;
}
struct poly // maybe : public polybase
{
~poly() { delete pb; }
char type() { return pb->type(); }
polybase *pb;
}
It might be possible to replace poly by a smart pointer.
This won't save you anything in numbers of allocations and
deallocations.
Bernd Strieder