Why is “boost::function = boost::bind(…)” creating 13 temporaries?

蹲街弑〆低调 提交于 2019-11-30 22:59:25

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!