問題描述
根據http://en.cppreference.com/w/cpp/utility/functional/function/function,初始化器的類型,即形式(5)中的F
,應滿足CopyConstructible的要求.我不太明白這個.為什么 F
不能只是 MoveConstructible?
According to http://en.cppreference.com/w/cpp/utility/functional/function/function, the type of the initializer, i.e., F
in form (5), should meet the requirements of CopyConstructible. I don't quite get this. Why is it not OK for F
to be just MoveConstructible?
推薦答案
std::function 在內部使用類型擦除,因此 F 必須是可復制構造的,即使您使用的特定 std::function 對象從未被復制.
std::function uses type erasure internally, so F has to be CopyConstructible even if the particular std::function object you are using is never copied.
類型擦除工作原理的簡化:
A simplification on how type erasure works:
class Function
{
struct Concept {
virtual ~Concept() = default;
virtual Concept* clone() const = 0;
//...
}
template<typename F>
struct Model final : Concept {
explicit Model(F f) : data(std::move(f)) {}
Model* clone() const override { return new Model(*this); }
//...
F data;
};
std::unique_ptr<Concept> object;
public:
template<typename F>
explicit Function(F f) : object(new Model<F>(std::move(f))) {}
Function(Function const& that) : object(that.object->clone()) {}
//...
};
您必須能夠生成 Model
,這會強制 F 為 CopyConstructible.
You have to be able to generate Model<F>::clone()
, which forces F to be CopyConstructible.
這篇關于為什么 std::function 的初始化程序必須是可復制構造的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!