
Hello all, I just wanted to get some opinions on the following static allocation policy, revamped to ensure that there won't be alignment problems. Does anything need to be revised? template < typename Type > class AllocateStatically { public: typedef Type * Pointer; static Pointer Create ( ) { static Type instance; static bool first = true; if ( first ) { first = false; } else { new ( reinterpret_cast < Pointer > ( &instance ) ) Type; } return &instance; } static void Destroy ( Pointer p ) { p->~Type ( ); } }; -Jason

"Jason Hise" wrote:
I just wanted to get some opinions on the following static allocation policy, revamped to ensure that there won't be alignment problems. Does anything need to be revised?
template < typename Type > class AllocateStatically { public: typedef Type * Pointer;
static Pointer Create ( ) { static Type instance; static bool first = true;
if ( first ) { first = false; } else { new ( reinterpret_cast < Pointer > ( &instance ) ) Type; }
return &instance; }
static void Destroy ( Pointer p ) { p->~Type ( ); } };
It is wrong IMHO because: 1. The Type needs default constructor 2. The Type instance gets always created (and possibly recreated again) 3. The first Typeinstance may be "destroyed" w/o calling destructor. Alexandresu uses union aligned to fit anything with sizeof(Type): template <class T> struct CreateStatic { union MaxAlign { char t_[sizeof(T)]; short int shortInt_; int int_; long int longInt_; float float_; double double_; long double longDouble_; struct Test; int Test::* pMember_; int (Test::*pMemberFn_)(int); }; static T* Create() { static MaxAlign staticMemory_; return new(&staticMemory_) T; } static void Destroy(T* p) { p->~T(); } }; /Pavel

Pavel Vozenilek wrote:
It is wrong IMHO because: 1. The Type needs default constructor
This is a singleton allocator... because singletons manage their own lifetime, aren't default ctors the only kind that make sense?
2. The Type instance gets always created (and possibly recreated again)
I thought that it would only be created the first time control enters the function.
3. The first Typeinstance may be "destroyed" w/o calling destructor.
Except that where this class is used (by the singleton), calls to create and destroy will always be matched...
Alexandresu uses union aligned to fit anything with sizeof(Type)...
He also mentions that this is not technically portable according to the standard. I'd prefer to avoid such things, which seem like hacks to me, if at all possible. -Jason
participants (2)
-
Jason Hise
-
Pavel Vozenilek