I have some pretty basic test code. I have a class that just logs all operations on it. I bound it to a boost::function
object like this:
void Function(const Foo&)
{
printf("Function invoked\n");
}
// ...
boost::function<void(void)> func;
{
Foo f;
printf("\nConstructing function\n");
func = boost::bind(&Function, f);
printf("Construction complete\n\n");
}
I expect that the function object contains a copy of f
. So creating at least one copy is mandatory. However, I find that I get 13 temporaries. Output is:
Constructing function
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::~Foo
Foo::Foo(const Foo&)
Foo::~Foo
Foo::~Foo
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::Foo(const Foo&)
Foo::~Foo
Foo::~Foo
Foo::~Foo
Foo::~Foo
Foo::~Foo
Foo::Foo(const Foo&)
Foo::~Foo
Foo::Foo(const Foo&)
Foo::~Foo
Foo::~Foo
Foo::~Foo
Foo::~Foo
Construction complete
I can't use ref
or cref
because I do need it to make a copy of the object. Am I doing something horribly wrong? Or do I need to use a wrapper (like boost::shared_ptr
) to avoid an absurd number of copies?
Full code and problem demonstration can be found on Codepad.
If you remove the "func = " assignment part the number of copies are lowered to 4 which is quite better than 13.
template <class F>
void callF(F fun)
{
}
callF(boost::bind(&func, fl));
So the solution is simple - don't use boost::function
来源:https://stackoverflow.com/questions/14617835/why-is-boostfunction-boostbind-creating-13-temporaries