我想构建一个可调用的对象链,以后可以异步执行。我想尝试以下方法:构建节点的“嵌套”结构(通过将每个节点移动到其“父”中)导致存储所有计算的对象,并且可以按需启动链。将`std :: move(* this)`安全到`this-> some_method`创建的对象中吗?
这是我脑子里想的:
template <typename TParent, typename TF>
struct node
{
TParent _parent;
TF _f;
node(TParent&& parent, TF&& f)
: _parent{std::move(parent)}, _f{std::move(f)}
{
}
template <typename TFContinuation>
auto then(TFContinuation&& f_continuation)
{
using this_type = node<TParent, TF>;
return node<this_type, std::decay_t<TFContinuation>>
{std::move(*this), std::move(f_continuation)};
// ^^^^^^^^^^^^^^^^
// ...safe?
}
};
上面的代码将允许用户编写类似链下列之一:
int main()
{
node n{some_root_callable, []{/*...*/}};
n.then([]{/*...*/})
.then([]{/*...*/})
.then([]{/*...*/})
.then([]{/*...*/});
}
(真正的实现将支持更多的有用抽象如when_all(...)
或when_any(...)
。)
假设TParent
,TF
,和TFContinuation
是可移动的可调用的对象,是安全(即明确定义)到的node::then
调用期间调用std::move(*this)
?
这真的取决于你将如何使用'*此搬家后。如果你没有破坏任何东西(也就是说,将对象的状态保留在析构函数无法处理的状态),我看不到问题。 –
'std :: move'不会移动任何东西,所以在_move_之后你可以做什么主要取决于'TParent'的构造函数实际上做了什么。也就是说,你可以删除'this'指针并且仍然可以避开它。只要你没有玩过_move_之后剩下的东西,我看不出有什么理由不能做到这一点。 – skypjack