确定在使用std::函数对象时如何分配外部内存



有没有办法确定如何分配std::function对象的外部内存?如果使用原始C函数指针馈送std::function,则它可能不会分配外部内存,但它可能会获得std::bind()对象,并且它不准备存储任何大小的复制的std::function对象,因此在这种情况下,它必须分配外部内存。

有没有办法确定如何分配std::function对象的外部内存?

不,没有——至少不再有了(自C++17以来(,请参阅有问题的评论。

我需要函数<gt-对象,因为它们可以存储一个完整的可调用对象及其内容,如果是bind((对象,则为其提供参数

好吧,您可以总是重写标准模板,并以适合您自己需求的方式修改它们的行为。复制目标(例如bind对象(并提供operator()(其本身调用bind对象(的模板类怎么样?你可以在那里提供自己的内存管理:

class Function
{
class WrapperBase
{
virtual ~WrapperBase() { }
virtual void operator()() = 0; // with appropriate return type
// and parameters – you could make
// Function a template for
};
template <typename T>
class Wrapper
{
T m_t;
public:
Wrapper(T& t) : m_t(t) { }
void operator()() override
{
m_t();
}
};
public:
template <typename T>
Function(T& t)
{
void* memory = nullptr; // your personal memory allocation instead
// consider correct size and alignment!
m_wrapper = new (memory) Wrapper<T>(t);
}
~Function()
{
m_wrapper->~Wrapper(); // destructor needs to be called explicitly
// free the memory of m_wrapper according to your personal
// allocation strategy
}

void operator()()
{
(*m_wrapper)();
}
private:
WrapperBase* m_wrapper;
};

这个例子是不完整的,没有考虑T的常量、移动构造等——你可能想自己添加。

您可能希望避免完全复制,只存储引用——或者专门化模板,使正常引用接收到的对象仅存储为引用,而右值引用接收的对象则被复制。无尽的可能性。。。

对于std::function的分配器支持在C++17中已被弃用,并且在C++17之前的库不太支持它。

例如,cppreference说:

std::函数的分配器支持指定不周,实现不一致。有些实现根本不提供重载(6-10([这些是支持分配器的构造函数],有些提供重载但忽略提供的分配器参数,还有一些提供重载并使用提供的分配器进行构造,但在重新分配std::函数时不提供。因此,C++17中删除了对分配器的支持。

@unddoch在对您的问题的评论中给出了相应的建议和更详细的解释。

因此,恐怕您的问题的答案是否定的。std::function中没有分配器支持。

最新更新