为什么 std::function 的初始化程序必须是可复制构造的?

2021-12-13 00:00:00 function constructor templates c++ c++11

根据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::clone(),这会强制 F 为 CopyConstructible.

You have to be able to generate Model<F>::clone(), which forces F to be CopyConstructible.

相关文章