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.
std::bind
does. – Karikariag++
, no special flags or options except-O2
. Tried with and without c++11, no difference. – Pieriastd::function
andstd::bind
, only two temporaries are created. – Pieriaboost::bind
has not been upgraded for C++11. – Ahouhstd::function
? The performance is faaaar better (at least the copies are a lot fewer). +1 from me. – Rosemaryrosemond