Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch std::function allocations at compile time

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?

like image 754
David Woo Avatar asked Aug 27 '15 16:08

David Woo


People also ask

Does std :: function allocate?

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.

Is std :: function slow?

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.

Does STD bind allocate?

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 .

What is compile time memory allocation?

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.


1 Answers

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()(...)
};
like image 99
Niall Avatar answered Sep 22 '22 12:09

Niall