tags:

views:

141

answers:

2

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.

+1  A: 

Wouldn't it be cleaner just to take an extra reference so the deallocator is never called? (Although that's still not very clean.)

I can't say that there's no function in Boost which would do the job, but it doesn't sound like something they would want to include.

EDIT: Having read the comments and a little documentation, it boils down to this:

  1. Reference leaking. At some point, execute this:

    new shared_ptr( my_global_shared_ptr );
    

    Advantages: conceptually easy. Disadvantages: you are leaking something on the heap.

  2. Custom deallocator. Since shared_ptr requires little of the deallocator function, an anonymous identity function like that provided in the other answer would do fine.

    Advantages: leverages Boost and has absolutely no overhead. Disdvantages: requires a little documentation.

  3. Non-static global object. If there is a global shared_ptr for your object, that should be the only means of access to it. Replace the declaration of the global with a shared_ptr intialized by new my_class. I think this is best.

Potatoswatter
How would you go about taking an extra reference? I didn't think `shared_ptr`s count was accessible.
Mark Ransom
@Mark Ransom: I think he means copy the `shared_ptr` and store it somewhere.
Billy ONeal
Yeah, but that extra copy will be destroyed eventually. Doesn't seem very practical.
Mark Ransom
Anything is possible. `new shared_ptr( my_global_shared_ptr );` Leak it.
Potatoswatter
I prefer not to have leaks in my programs if I can help it. You're just trading one problem for another.
Mark Ransom
+2  A: 

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.

scjohnno
That would fall into the *"I don't want to sprinkle my code"* category.
Georg Fritzsche
This solution involves more sprinkling than using a hypothetical boost::no_op_deallocator() in place of the boost::lambda::_1?
scjohnno
A very clever solution, but I think I'd prefer to have the trivial function somewhere and give it a descriptive name.
Mark Ransom
@scjohnno: Well, he asked for a stock `shared_ptr` specific solution and that would be one of the possible trivial non-stock solutions.
Georg Fritzsche