为什么是“boost :: function = boost :: bind(...)”创造13个临时? [英] Why is "boost::function = boost::bind(...)" creating 13 temporaries?

查看:130
本文介绍了为什么是“boost :: function = boost :: bind(...)”创造13个临时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些很基本的测试代码。我有一个类,只记录所有的操作。我将它绑定到 boost :: function 对象,如下所示:

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");
    }



我希望函数对象包含 f 。所以创建至少一个副本是强制性的。但是,我发现我获得了 13 个临时数据。输出为:

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

我不能使用 ref cref 需要它来创建对象的副本。我做一些可怕的错误吗?或者我需要使用包装器(如 boost :: shared_ptr )来避免荒谬的副本数量?

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.

推荐答案

如果删除func =分配部分,则将副本数降低到4,这比13好得多。

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));

所以解决方案很简单 - 不要使用boost :: function

So the solution is simple - don't use boost::function

这篇关于为什么是“boost :: function = boost :: bind(...)”创造13个临时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆