
-----Original Message----- From: boost-bounces@lists.boost.org [mailto:boost-bounces@lists.boost.org] On Behalf Of Jason Hise Sent: Saturday, January 08, 2005 11:56 AM To: boost@lists.boost.org Subject: Re: [boost] Re: Singleton
Here is a stripped down example of what I am trying (destruction would be virtually identical, and thus is omited):
template < typename T > class AllocateUsingNew { public: static T * Create ( ) { T * p = reinterpret_cast < T * > ( new char [ sizeof ( T ) ] ); try { return T :: Allocation :: Construct ( p ); } catch ( ... ) { delete [] reinterpret_cast < char * > ( p ); throw; } } };
template < typename T, typename A = AllocateUsingNew < T > > class Singleton { public: class Allocation { private: friend A; // allow the allocator access to Allocation::Create
static void Create ( T * p ) { T :: Create < T > ( p ); // call the derived specialization? } };
friend Allocation; // allow allocation access to Create
protected: template < typename T > static void Create ( T * p ); // undefined base template that derived should inherit };
template < typename T > void T :: Create < T > ( T * p ) // specialize derived's Create method? { new ( p ) T; }
Any suggestions?
Your Create() function in AllocateUsingNew isn't guaranteed to work for all classes. The type of the singleton class might have alignment restrictions. char has no alignment restrictions; therefore, the program may crash when trying to initialize the singleton. I believe boost::aligned_storage is your friend in this situation. -- Noah