我想了解std::function
的實現是如何工作的。爲了簡單起見,我們考慮不帶參數的移動功能。像std :: function這樣的自毀型擦除類是如何實現的?
我明白std::function
通過典型的類型擦除技術,清除其目標的類型:
template<class Result>
struct function
{
public:
template<class Function>
function(Function&& f)
: f_(std::make_unique<callable_base>(std::forward<Function>(f)))
{}
// XXX how to implement constructor with allocator?
template<class Alloc, class Function>
function(const Alloc& alloc, Function&& f);
Result operator()() const
{
return (*f_)();
}
private:
struct callable_base
{
virtual Result operator()() const = 0;
virtual ~callable_base(){}
};
template<class Function>
struct callable
{
mutable Function f;
virtual Result operator()() const
{
return f;
}
};
// XXX what should the deleter used below do?
struct deleter;
std::unique_ptr<callable_base, deleter> f_;
};
我想延長這種類型的功能,以支持自定義配置。我需要清除分配器的類型,但是使用std::unique_ptr
很困難。給定unique_ptr
的自定義刪除程序需要知道爲構造函數提供的Function
的具體類型,以便能夠正確釋放其存儲。我可以使用另一個unique_ptr
來刪除刪除器,但該解決方案是循環的。
好像callable<Function>
需要釋放自己。什麼是正確的方法來做到這一點?如果我在callable<Function>
的析構函數中釋放內存,那似乎爲時過早,因爲它的成員仍然活着。
請注意,分配器對'std :: function'的支持正在C++ 17中被刪除。 – Brian