Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "boost::function = boost::bind(...)" creating 13 temporaries?

Tags:

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.