Cort Ammon
Cort Ammon

Reputation: 10903

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

Quite often I want to write higher order functional code like

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

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

In cases like these, I would like to be able to guarantee that the std::function constructor does not allocate any memory. The guarantees in the spec are... hard to read. There seems to be some guarantees surrounding reference_wrapper, but I have not been able to get them to work cleanly, due to what I think are lvalue vs rvalue issues. I end up with

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

In many of these cases, I want to leverage virtual functions, so I can't just template these issues away (although I have played with using a wrapper that accepts the lambda type as an argument, and wraps it with std::ref, sidestepping any issues regarding temporaries)

What is the minimum amount of syntactic boilerplate needed to ensure this pattern does not allocate any memory?

Upvotes: 3

Views: 120

Answers (1)

SergeyA
SergeyA

Reputation: 62603

There are no guarantees of allocations (or lack of thereof) specified in the standard for std::function constructors. Most you can hope for is a recommendation, from 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.

So your best bet would be to look at your implementation and check when allocation does not happen.

Upvotes: 3

Related Questions