使std :: function需要复制构造函数的基本原理 [英] Rationale behind making std::function require copy constructor
问题描述
我最近试图做这样的事情:
I lately tried to do something like this:
auto x = std::make_unique<int>(1);
auto l = [y = std::move(x)]() { return *y; };
std::function<void()> f(std::move(l)); //error, requires copy construction
令我非常失望和困惑的是,它在我的脸上抛出了一堆错误消息.如您所知, std :: function
禁止使用不可复制构造的类型进行构造.是否有特定的原因呢?还是在标准中被忽略了?仅移动类型的构造会带来哪些问题?
And to my huge disappointment and confusion it threw a bunch of error messages in my face. As you already know, std::function
disallows construction from types that are not copy-constructible. Is there a specific reason why is it so? Or is it an overlook in the standard? What problems would construction from move-only types impose?
推荐答案
std :: function
可以进行仅移动的可调用,但只能将其自身限制为始终只能移动.它使用类型擦除来存储对象,因此它的静态行为必须表示它所存储的对象所需的最低公分母功能.
std::function
could take a move-only callable, but only by restricting itself to being move-only always. It uses type-erasure to store the object, so its static behavior must represent the lowest-common-denominator functionality that it requires of the objects it stores.
这是事实:C ++及其标准库中有很多地方希望可调用对象是可复制的.所谓很多",是指整个标准算法库.甚至C ++ 20概念 indirect_unary_predicate
都需要 copy_constructible
.从本质上讲,所有算法都可以随意复制给定功能.他们甚至可以通过 value 来实现这些功能.
Here's the thing though: there are a lot of places in C++ and its standard library that expect that a callable shall be copyable. And by "lot", I mean the entirety of the standard algorithms library. Even the C++20 concept indirect_unary_predicate
requires copy_constructible
. Essentially, all algorithms are given the freedom to copy the given function at will; they even take those functions by value.
只能移动的 std :: function
类型不能与任何此类算法一起使用.而且,仅移动是 std :: function
采取仅移动类型的唯一方法.
A move-only std::function
type could never be used with any such algorithm. And being move-only is the only way for std::function
to take move-only types.
这篇关于使std :: function需要复制构造函数的基本原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!