gpt4 book ai didi

c++ - 是否可以直接接受 `std::bind` 的输出作为值,而不转换为 std::function?

转载 作者:太空狗 更新时间:2023-10-29 20:36:57 37 4
gpt4 key购买 nike

This answer声明 std::bind 按值返回一个对象,并且 this comment暗示分配给 std::function 将导致堆分配存储 std::bind 返回的值。

有没有办法避免这种堆分配,将std::bind的返回值直接按值传递给另一个函数?

如果是这样,方法签名将用什么替换 std::function


更明确地说,我有一个如下所示的函数。

void runThisFunction(std::function<void()> func);

假设有一个具有以下签名的函数 foo

void foo(int a, int b);

现在,我将按如下方式调用 runThisFunction

runThisFunction(std::bind(foo, 1, 2));

在此调用中,std::bind 的输出被转换为 std::function,动态内存分配作为此过程的一部分发生。

是否可以将 std::function 替换为一些其他声明,这些声明将直接按值接收 std::bind 的输出,从而避免动态内存分配?

最佳答案

Is it possible to replace std::function with some other declaration that would would receive the output of std::bind directly by value, thereby avoiding the dynamic memory allocation?

是的;但是 std::bind 返回的类型是未指定的,所以你需要使用模板来捕获类型;

template <typename F>
void runThisFunction(F func);

关于内存分配...

In this invocation, the output of std::bind is converted into an std::function, and dynamic memory allocation occurs as part of this process.

可以使用动态内存(但不能使用 always ),这取决于绑定(bind)到 std::function 中的仿函数的大小和实现的质量。

此外,C++ 规范有这个 §20.12.12.2.1/11 ;

[Note: Implementations are encouraged to avoid the use of dynamically allocated memory for small callable objects, for example, where f is an object holding only a pointer or reference to an object and a member function pointer. — end note ]

即使有内存分配,我也不会太在意。除非代码对性能至关重要并且您已经对其进行了测量,否则所需的间接访问应该不是问题。

请记住,对于您的情况,bind 中绑定(bind)的 foo 是一个指针,很可能无论如何都不会进行动态内存分配。


I started looking at this because I measured cache misses on the conversion due to unexpected slowness detected through instrumentation

因此,您对性能有一些可衡量的担忧……有一些替代方法可以将 std::bindstd::function 结合使用。 std::bind 是有用的通用 Binder ,但这并不意味着它的性能也足够好 - 制作您自己的。自定义仿函数可能性能更高。基于 lambda 的实现也很好看。不要忘记函数 foo 也可以与 std::function 一起使用,然后你就完全放弃了仿函数/绑定(bind)器(注意,签名需要匹配).


在上述引用中提到的“小对象”优化开始之前,关于对象需要多“小”的附注似乎在库实现之间略有不同。 p>

这里是coliru (libstdc++),std::function 的参数大小需要为 16 个字节或更少,在 MSVC 上,限制是 32 字节(这两个看起来都是 32 位平台)。使用 clang++ (libc++) 64 位编译时,此限制为 24 字节......这实际上取决于实现,在需要进行分配之前,它们将允许多少空间。

我不确定性能有多重要,但也可以为您的目标计算此限制,然后应用优化,使 std::function 的参数保持低于这些限制;例如使用指向 struct 的指针或引用(也 std::ref)作为参数(但必须注意不要将它们悬空)。

关于c++ - 是否可以直接接受 `std::bind` 的输出作为值,而不转换为 std::function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617358/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com