c++ - 为什么我不能移动包含已移动 future 的可变函数?

标签 c++ lambda mutable move-constructor

我基本上正在尝试这样做:

using Type = SomeTypeThatIWantToMove;

std::promise<Type> promised_result;
std::future<Type> promised_future = promised_result.get_future();

using Callback = std::function<void()>;

Callback function_which_should_be_movable =
            [this, future_result(std::move(promised_future))]() mutable
{
    this->some_function(future_result.get());   // signature: void some_function(const Type&)
};

using ResultBuilder = std::function<Type(Callback&&)>;

// result_builder is of type ResultBuilder  
Type thingy = result_builder(std::move(function_which_should_be_movable));

MinGW 告诉我,function_which_should_be_movable 的 Move-Constructor 被删除,因为 std::future 的 Copy-constructor 被删除。但是,我不明白为什么编译器会尝试复制 future 而不是移动它。

最佳答案

function_which_should_be_movable类型为std::function 。根据cppreference :

template< class F > function( F f ); F must meet the requirements of Callable and CopyConstructible.

您尝试用来构造 std::function 的 lambda 表达式对象不可复制,因此出现问题。

至于为什么std::function有这个需求,请看这个问题:Why the initializer of std::function has to be CopyConstructible? (这是我自己问的)。简单来说,std::function使用的类型删除技术将实例化 F 的复制构造函数。无论您是 std::function 的用户,这种情况都会发生。对象,实际上是否使用了这个复制构造函数。

关于c++ - 为什么我不能移动包含已移动 future 的可变函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29847443/

相关文章:

kotlin - 如何将 lambdas 链接到 Kotlin 中的结果 lambda?

F# byref 参数不可变

c++ - 从二维数组 C++ 中提取行或列

c# - 异步匿名无参数方法作为方法参数

C++:我怎样才能重载一个函数,以便它可以接受任何仿函数,包括指向成员函数的指针?

c++ - 使不可变类型可变(consts 和 boost)

java - 创建不可变类时,集合是否应该只包含不可变对象(immutable对象)?

c++ - 我没有以秒为单位得到耗时

c++ - 这是部分模板特化吗?

c++ - 转换构造函数