Boost logo

Boost :

From: Noah Stein (noah_at_[hidden])
Date: 2005-01-10 15:52:17


> -----Original Message-----
> From: boost-bounces_at_[hidden] [mailto:boost-bounces_at_[hidden]]
> On Behalf Of Jason Hise
> Sent: Saturday, January 08, 2005 11:56 AM
> To: boost_at_[hidden]
> 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
 


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk