我基本上正在尝试这样做:
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 ofCallable
andCopyConstructible
.
您尝试用来构造 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/