Why the initializer of std::function has to be CopyConstructible?(为什么 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,这会强制 F 为 CopyConstructible.
You have to be able to generate Model<F>::clone(), which forces F to be CopyConstructible.
这篇关于为什么 std::function 的初始化程序必须是可复制构造的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 std::function 的初始化程序必须是可复制构
基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
