What is the correct way to reuse the return value of a boost::bind call?

265 views Asked by At

I have to following code:

class Timer;
typedef boost::signals2::signal<void (void)> signal_type;

void Timer::create(long expiration, signal_type::slot_type const& slot);

The normal usage of that is to call,

timer.create(2000, boost::bind(&some_callback));

and that works correctly.

However, now I need to 'restart' this timer a lot, which would require a lot of calls to boost::bind(&some_callback) -- I don't want to do that because that seems a waste of CPU.

I would like to do the call to boost::bind once and then reuse whatever it returned on subsequent call to the create() function. I'm not sure if this can work though. I can imagine that it will leak memory and worse, use freed memory and crash or something.

I think that the above should be sufficient information to give a general answer, but let me add information about what this 'create' function exactly does.

The effect of calling create() is that an object 'Signal' is created with new, where Signal is:

struct Signal {
    signal_type mSignal;
};

and then mSignal is connected to the slot value passed to create:

mCallback = new Signal;
mCallback->mSignal.connect(slot);

When I have to 'restart' the timer (before it expires), I first call a cancel() function, and then call create() again. The function cancel() effectively calls 'delete mCallback' - so, doesn't do anything else than freeing the memory allocated by the 'new' call above.

Hence, I guess that storing the return value of boost::bind and repeatedly using it effectively comes down to:

signal_type::slot_type slot(boost::bind(&callback));
while (--several_times)
{
  signal_type* signal = new signal_type;
  signal->connect(slot);
  delete signal;
}

Is that allowed, or do the calls to 'connect' and delete do something to 'slot' so I can't reuse it without side effects?

1

There are 1 answers

0
sehe On

In general,

  • bind expressions are pretty lightweight (the compiler would usually inline the whole shebang)
  • bind expressions do copy their bound parameters, but this is easily mitigated doing boost::bind(&MyClass::fpp, boost::ref( object))
  • boost::function<> and std::function<> are ideally suited to storing bound expressions:

    boost::function<void()> stored_bind = 
          boost::bind(&MyClass::fpp, boost::ref(object));