I want to only allow use of std::function in my code base if it does not do any allocations.
To this end I can write something like the function below and only use it to create my function instances:
template< typename Functor>
std::function<Functor> makeFunction( Functor f)
{
return std::function<Functor>(std::allocator_arg, DummyAllocator(), f);
}
where DummyAllocator will assert or throw if it ever gets used at runtime.
Ideally though I would like to catch allocating use cases at compile time.
i.e.
template< typename Functor>
std::function<Functor> makeFunction( Functor f)
{
static_assert( size needed for function to wrap f < space available in function,
"error - function will need to allocate memory");
return std::function<Functor>(f);
}
Is something like this possible?
But if your function object has no data and uses the builtin copy constructor, then std::function won't allocate. Also, if you use a function pointer or a member function pointer, it won't allocate.
Code wrapped into std::function is always slower than inlining code directly into calling place. Especially if your code is very short, like 3-5 CPU instructions.
The std::bind will be copied into heap allocated by the std::function and the std::function will be copied into heap allocated by the std::vector .
When a variable is declared compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation. Memory can be allocated for data variables after the program begins execution. This mechanism is known as runtime memory allocation or dynamic memory allocation.
The factory method you have is probably your best bet.
If not suitable, you may choose to implement an adaptor for function
; implement the interface with the std::function
as a member variable such that the adaptor enforces your constraints.
template <typename S>
class my_function {
std::function<S> func_;
public:
template <typename F>
my_function(F&& f) :
func_(std::allocator_arg, DummyAllocator(), std::forward<F>(f))
{}
// remaining functions required include operator()(...)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With