使用std :: function移动语义 [英] Move semantic with std::function

查看:76
本文介绍了使用std :: function移动语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: function 提供了右值引用的构造函数。
按标准移动的函数对象会发生什么?它会是空的,以便再次调用没有效果吗?

std::function provides a constructor from an rvalue ref. What happens to the moved function object by standard? Will it be empty so that calling it again has no effects?

推荐答案

在20.8.11.2.1p6下, function(function& f)使 f 处于未指定值的有效状态

Under 20.8.11.2.1p6, function(function &&f) leaves f in a valid state with an unspecified value.

空状态是有效状态,因此您应该期望移出的函数对象可以为空。

The empty state is a valid state, so you should expect that the moved-from function object can be empty.

由于函数执行类型擦除,并且函数对象可以任意昂贵,因此将移出的对象保留为空的优化很有意义:

Because function performs type erasure, and function objects can be arbitrarily expensive, the optimisation to leave the moved-from object empty makes sense:

std::function<void()> g{std::bind{f, std::array<int, 1000>{}}};
std::function<void()> h{std::move{g}};

h 被构造后 g ,可能会期望包含的 bind 已从 g h 而不是复制,因此 g 将留空。

After h has been constructed by move from g, one would expect the contained bind have been transferred from g to h rather than copying, so g would be left empty.

对于以下程序,gcc 4.5.1打印

For the following program, gcc 4.5.1 prints empty:

#include <functional>
#include <iostream>
void f() {}
int main() {
    std::function<void()> g{f}, h{std::move(g)};
    std::cout << (g ? "not empty\n" : "empty\n");
}

这不一定是最理想的行为;内联小的可调用对象(例如函数指针)会导致以下情况:复制可调用对象比移动可调用对象和清空已移动的对象要有效,因此另一种实现可能会将 g 留在非空可调用状态。

This is not necessarily the most optimal behaviour; inlining small callables (e.g. function pointers) creates a situation where copying the callable is more efficient than moving it and emptying the moved-from object, so another implementation could leave g in a non-empty callable state.

这篇关于使用std :: function移动语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆