Re: Factory and placement new
jpa wrote:
class Factory
{
public:
virtual Base* create(int arg1, int arg2)
{
if( !free_ )
return new Derived(arg1, arg2);
Base* ptr = ...; // extract from free list
ptr->~Base();
new (ptr) Derived(arg1, arg2);
return ptr;
};
virtual void release(Base* ptr)
{
// add ptr to free list
};
};
Does this work?
In this case, it'll probably work, but it makes a lot of assumptions.
This biggest assumption is that sizeof(Derived) == sizeof(Base), which
in general won't be the case.
If you make your factory a template, then you can make the freelist of
the type of thing you want to create:
// base class for all factories so you can put 'em
// in a list together easily.
class FactoryBase
{
public:
virtual Base* create(args)=0;
virtual void release(Base*)=0;
};
template <typename T>
class Factory : public FactoryBase
{
public:
Base* create(args)
{
T* object = freelist_.GetOne();
if (object == NULL)
object = new T(args);
return object;
}
void release(Base* object)
{
bool deleted = freelist_.ReturnOne(object);
if (!deleted) // maybe it's not owned by the freelist?
delete object;
}
private:
T freelist_[NUM_OBJECTS];
};
My own humble guess is that this works and is quite safe if you only
have a single factory object in use at a time...
That would not be the case. It works with any number of factories in
use at a time, but requires that the derived classes are exactly the
same size and alignment as the Base type. ...unless you're doing some
other trickery to build the freelist, in which case you probably don't
need to destroy the Base object (e.g. you compute the max size for a
derived class, and make a char array that's NUM_ENTRIES *
sizeof(LARGEST_DERIVED_CLASS). Then you will need to do placement new
and explicitly call the DERIVED destructor on release...
Do you find any other pitfalls or reasons why I shouldn't do this?
Yeah, calling the destructor on objects that you didn't call placement
new on originally seems like pretty bad form. The Microsoft standard
library did this a few years ago in their exception assignment code,
and it was no end of the stupidness that I had to endure to work
around that particular little joy.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]