Boost logo

Boost :

From: E. Gladyshev (egladysh_at_[hidden])
Date: 2003-09-02 16:52:18


--- Gregory Colvin <gregory.colvin_at_[hidden]> wrote:
[...]

> > 3. If your class is using STL containers, use boost::memory::allocator
> > adapter (see bellow).
>
> Why not just use std::allocator?

Because boost::memory::allocator will use UserAllocator under the covers.
So if you customized UserAllocator parameter, you customized
how STL allocate their memory as well.

>
> > 4. To construct/destroy objects, use boost::memory::construct/destroy.
>
> See below.
>
> > 5. Avoid using explicit references to allocators.
> >
> > ... Usage example:
> > ==============
> > template< typename T, typename UserAllocator =
> > boost::default_user_allocator_new_delete >
> > class X
> > {
>
> What if you want X to use the same allocator as some other STL container
> constructed with a non-Boost allocator? That would be difficult unless
> you have [...]

Yes.

> > T* _p;
>
> How to pass arguments to T's constructor? Better just
>
> p = new(UserAllocator::malloc(sizeof T)) T(...)
>
> > }
> > ~X()
> > {
> > if( _p )
> > boost::memory::destroy<T, UserAllocator>( _p, 1 );
>
> In which case, why not just
>
> p->~T(), UserAllocator::free(p);
>
> ?

The boost::memory::construct/destroy are just convinience wrappers
that will do like just that.
They can also handle exceptions properly.

struct memory
{

template< typename T, typename A >
static void destroy( T* p )
{
  try
  {
    p->~T();
    A::free(p);
  }
  catch( ... )
  {
    A::free(p); //free memory even if the destructor crashes.
    throw;
  }
}

};

Eugene

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com


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