为什么 std::function 的初始化程序必须是可复制构造的? [英] Why the initializer of std::function has to be CopyConstructible?

查看:27
本文介绍了为什么 std::function 的初始化程序必须是可复制构造的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据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.

这篇关于为什么 std::function 的初始化程序必须是可复制构造的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆