Why the initializer of std::function has to be CopyConstructible?

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()) {}
    //...

};

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

Leave a Comment