在编译时捕获std::函数分配
catch std::function allocations at compile time
我想只允许在我的代码库中使用std::function,如果它不做任何分配。
为此,我可以编写类似下面的函数,并且只使用它来创建我的函数实例:
template< typename Functor>
std::function<Functor> makeFunction( Functor f)
{
return std::function<Functor>(std::allocator_arg, DummyAllocator(), f);
}
如果DummyAllocator在运行时被使用,它将断言或抛出。
理想情况下,我希望在编译时捕获分配用例。
。
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);
}
这样的事情可能吗?
您拥有的工厂方法可能是您最好的选择。
如果不合适,您可以选择为function
实现适配器;使用std::function
作为成员变量实现接口,以便适配器执行约束。
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()(...)
};
我会写一个不分配的std::function
替代品,因为std::function
会在需要时分配内存,这里有一个候选。
给定库中支持std::function
分配器,只需为std::function
提供一个不能工作的分配器。
template< typename t >
struct non_allocator : std::allocator< t > {
t * allocate( std::size_t n ) { throw std::bad_alloc{}; }
void deallocate( t * ) {}
non_allocator() = default;
template< typename u >
non_allocator( non_allocator< u > const & ) {}
template< typename u >
struct rebind { typedef non_allocator< u > other; };
};
template< typename t, typename u >
bool operator == ( non_allocator< t > const &, non_allocator< t > const & )
{ return true; }
template< typename t, typename u >
bool operator != ( non_allocator< t > const &, non_allocator< t > const & )
{ return false; }
不幸的是,这在GCC中不起作用,因为它甚至没有为function
声明任何allocator_arg
构造函数。即使在Clang中,编译时错误也是不可能的,因为它不幸地使用运行时if
对常量值来决定是否使用分配器。
相关文章:
- 当我尝试通过构造函数分配 char 数组时出现错误
- c++如何为类成员函数分配内存
- 如何将析构函数分配给指针
- 当我们在C++中创建类的对象时,为成员函数分配的内存在哪里?
- 将来自类的特定实例的函数分配给变量以保持状态
- 为什么我不能使用已删除或私有析构函数分配类的数组?
- 如何将 gmock 函数分配给特定的函数指针
- 将成员函数分配给实例成员的属性
- 当设置对象等于另一个函数的返回值时,为什么要调用移动构造函数/分配
- 尝试将返回无符号值的函数分配给指向无符号的指针时,继续获取 SIGSEGV
- 当 lambda 函数必须访问其他成员时,如何将该函数分配给结构成员
- 将 lambda 函数分配给静态成员变量 (c++)
- 如何安全地释放构造函数分配的资源
- 如何将函数分配给函数指针?
- 是否可以在基类中删除复制和移动构造函数/分配运算符
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 为什么从工厂函数分配向量并在循环中迭代它会导致段错误
- 如何在隐式复制构造函数/分配运算符中压制成员
- 在将函数分配给函数指针时,为什么可以多次使用取消任务运算符
- C 将成员对象函数分配给类成员功能