views:

29

answers:

1

Is it somehow possible to use boost::object_pool<>::construct with non const references?

The following snippet doesn't compile (VS2010):

foo::foo(bar & b)
{
}

static boost::shared_ptr<foo> foo::create(bar & b)
{
  return boost::shared_ptr<foo>(foo_pool.construct(b),
    boost::bind(& boost::object_pool<foo>::destroy, & foo_pool, _1));
}

VS2010 complains about not being able to convert bar & to const bar &. Looking at boost::object_pool<>::construct the reason ist clear:

element_type * construct(const T0 & a0)

I can't make the ctor parameter const though. Is there a trick to make boost::object_pool<> work with my foo class?

+3  A: 

Use boost::ref:

static boost::shared_ptr<foo> foo::create(bar & b)
{
  return boost::shared_ptr<foo>(foo_pool.construct(boost::ref(b)),
    boost::bind(& boost::object_pool<foo>::destroy, & foo_pool, _1));
}

boost::ref makes a reference_wrapper. Because that uses a pointer, it can be copied around however you wish, and implicitly dereferenced into a reference to the original value.

GMan