Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No-op deallocator for boost::shared_ptr

Tags:

c++

boost

Is there a stock no-op deallocator in Boost to use with boost::shared_ptr for static objects, etc.

I know it's ultra-trivial to write, but I don't want to sprinkle my code with extra tiny functions if there is already one available.

like image 942
Alex B Avatar asked Apr 26 '10 02:04

Alex B


2 Answers

Yes there is one here:

#include <boost/serialization/shared_ptr.hpp> // for null_deleter

class Foo
{
  int x;
};

Foo foo;
boost::shared_ptr< Foo > sharedfoo( &foo, boost::serialization::null_deleter() );

There is, of course, a danger with the fact that you need to know the function you call doesn't store the shared_ptr for later use, as it actually goes against the policy of shared_ptr in that the underlying object remains valid until that of the last instance of the shared_ptr.

like image 195
CashCow Avatar answered Oct 04 '22 11:10

CashCow


Solution uses Boost.Lambda:

#include <boost/shared_ptr.hpp>
#include <boost/lambda/lambda.hpp>

int main()
{
    int *p = new int(5);

    {
        boost::shared_ptr<int> sp(p, boost::lambda::_1);
    }

    delete p;
}

'boost::lambda::_1' creates an empty functor that takes one argument.

You'll probably want to put a //comment in there to let people know why you did it, though.

like image 20
scjohnno Avatar answered Oct 04 '22 13:10

scjohnno