Question

Boost::bind documentation states:

By default, bind makes a copy of the provided function object. boost::ref and boost::cref can be used to make it store a reference to the function object, rather than a copy.

I am seeing excessive news and deletes in my code when I use boost::bind with a pointer to a member function. The documentation is unclear to me whether boost::bind(&classname::functionname,...) makes a copy of the function.

Or maybe the question makes no sense and as it is converting a member function into a function object it obviously has to new the function object.

So my question is there a way I can bind to a member function and avoid the new and delete?

Was it helpful?

Solution

According to my experiments (boost 1.49), boost::bind does not use dynamic memory for its own implementation. With this code

#include <boost/bind.hpp>

int f(int a , int b) {
  return a>b ? a+b : a-b;
}

int main()
{
  auto a = boost::bind(f, _1, 2);
  return a(0);
}

I tried breaking on operator new variants in gdb and it didn't fire. So I suspect your problem is actually that boost::bind is making copies of either the bound arguments (compare the output of these two snippets) or the call arguments. Search for something among these that could allocate memory while copying, and try to get rid of it.

If you're using a C++11 compiler, you can get away with boost::bind completely and use a lambda function instead. The example would be transformed to

auto a = [&](int a1) { return f(a1, 2); }

That would only copy if you'd capture objects by value.

EDIT: With the code you posted, try changing the line in question to

TConstIterator pIt = std::find_if(rtContainer.begin(), rtContainer.end(), 
  boost::bind(&TValueType::bSameSocket, boost::cref(rtData), _1));
                                        ^^^^^^^^^^^

That should make it better; report if it doesn't.

OTHER TIPS

What gets copied is the pointer to that method, so no new/delete involved. What bind returns is a function object that gets created and destroyed at some point, but again no dynamic memory allocation.

As far as I can tell if you use boost::bind in code such as to create a function object to act as the predicate in a find_if the function object is newed and deleted and this is what was causing my code to run slowly.

My question was: is there a way I can bind to a member function and avoid the new and delete?

I worked around the boost::bind by iterating through the list myself calling a member function through a member function pointer.

The type of the member pointer function is derived from template parameters for the list and its stored data types, but the same technique works whether the types are templated or not.

This solution reduced the user perception of response for a particular action from 5 minutes to effectively immediately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top