Boost logo

Boost :

From: Pavel Vozenilek (pavel_vozenilek_at_[hidden])
Date: 2005-01-16 17:21:32


"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


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