Lambda到std ::函数转换性能 [英] Lambda to std::function conversion performance

查看:118
本文介绍了Lambda到std ::函数转换性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用lambda函数来异步调用引用计数对象上的方法:

I'd like to use lambda functions to asynchronously call a method on a reference counted object:

void RunAsync(const std::function<void()>& f) { /* ... */ }

SmartPtr<T> objPtr = ...
RunAsync([objPtr] { objPtr->Method(); });

创建lambda表达式显然会创建一个副本,但我现在有一个问题,将lambda表达式转换为 std :: function object也会创建一堆我的智能指针的副本,每个副本增加引用计数。

Creating the lambda expression obviously creates a copy but I now have the problem that converting the lambda expression to a std::function object also creates a bunch of copies of my smart pointer and each copy increases the reference count.

以下代码应显示此行为:

The following code should demonstrate this behavior:

#include <functional>

struct C {
    C() {}
    C(const C& c) { ++s_copies; }

    void CallMe() const {}

    static int s_copies;
};

int C::s_copies = 0;

void Apply(const std::function<void()>& fct) { fct(); }

int main() {
    C c;
    std::function<void()> f0 = [c] { c.CallMe(); };
    Apply(f0);
    // s_copies = 4
}

到正常之后,我想防止太多的引用操作的性能原因。我不知道所有这些复制操作来自哪里。

While the amount of references goes back to normal afterwards, I'd like to prevent too many referencing operations for performance reasons. I'm not sure where all these copy operations come from.

有没有办法用更少的智能指针对象来实现这一点?

Is there any way to achieve this with less copies of my smart pointer object?

Compiler是Visual Studio 2010。

Update: Compiler is Visual Studio 2010.

推荐答案

std :: function 可能不会像自定义函子一样快,直到编译器实现了一些严重的特殊处理的简单情况。

std::function probably won't be as fast as a custom functor until compilers implement some serious special treatment of the simple cases.

但引用计数问题是症状复制 move 是适当的。正如其他人在评论中指出的,MSVC没有正确实现 move 。您描述的用法只需要移动,而不是复制,因此不应该触及引用计数。

But the reference-counting problem is symptomatic of copying when move is appropriate. As others have noted in the comments, MSVC doesn't properly implement move. The usage you've described requires only moving, not copying, so the reference count should never be touched.

如果可以,请尝试使用GCC编译并查看问题走走。

If you can, try compiling with GCC and see if the issue goes away.

这篇关于Lambda到std ::函数转换性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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