使用 std::function 保证没有动态内存的最小语法

Minimum syntax to guarantee no dynamic memory with std::function

我经常想写高阶函数代码,比如

void f(int value, const std::function<void(int)>& callback);

int x, y=5;
f(y, [&](int result) { x = result; });

在这种情况下,我希望能够保证 std::function 构造函数不分配任何内存。规范中的保证……难以阅读。 reference_wrapper 似乎有一些保证,但由于我认为是左值与右值问题,我无法让它们正常工作。我最终得到

auto callback = [&](int result) { x = result; };
f(y, std::ref(callback));

在许多这样的情况下,我想利用虚函数,所以我不能只是将这些问题模板化(尽管我已经尝试使用接受 lambda 类型作为参数的包装器,并将其包装为std::ref,回避任何关于临时对象的问题)

确保此模式不分配任何内存所需的最少语法样板数量是多少?

标准中为 std::function 构造函数指定的分配(或缺乏分配)没有保证。您最希望得到的是来自 20.14.17.3.2 的推荐:

Recommended practice: Implementations should avoid the use of dynamically allocated memory for small callable objects, for example, where f refers to an object holding only a pointer or reference to an object and a member function pointer.

所以最好的办法是查看您的实现并检查分配何时没有发生。