c++ - 存储和传递 std::function - 按值还是按引用?

标签 c++ c++11 functor std-function

我不知道何时按值或引用传递/存储 std::function 对象,或者我是否需要以某种方式使用移动语义。我有一个存储两个 std::function 的结构对象:

struct Control{
    char key;
    std::function<void()> press;
    std::function<void()> release;
    Control(char key, std::function<void()> press, std::function<void()> release):
        key(key),press(press),release(release){}
}

我还有一个包含这些结构的 vector 的类,我想在一个类似于这个的函数中初始化它:

void Screen::init(Player& player){

    this->controls.push_back(Control(
        'W',
        [&player](){player.go(UP);},
        [&player](){player.stop(UP);}));

}

我希望能够将 lambda 表达式直接传递给 Control 构造函数,并最终重复执行此操作:

void Screen::update(){
    foreach (auto control : controls){
        if(...) 
            control.press();
        else if (...) 
            control.release();
    }
}

我在尝试实现这个想法时遇到了很多错误和崩溃,所以我需要知道

  • 应该 std::function是按(const?)引用存储,还是按值存储,考虑到它们捕获引用?
  • 它们应该通过(const?)引用或值(或以某种方式移动)传递给 Control 构造函数吗?
  • 以这种方式将控件按值存储在 vector 中是否合适,或者我是否需要使用替代方法(unique_ptr<Control> 等)?
  • 当我循环访问控件 vector 时,我应该按值还是按引用访问它们?

假设 Player&对象始终在 Screen::update() 的范围内.

最佳答案

Should the std::functions be stored by (const?) reference, or by value, taking into account they capture a reference?

Lambda 应该按值存储。它们很小,很容易复制。

复制时要检查的唯一潜在问题是是否有任何捕获的值不存在或本身不可复制。 More info on this here .

在您的情况下,Player 仍将存在,复制引用就可以了。

Should they be passed to the Control constructor by (const?) reference, or value, (or moved, somehow)?

出于与上述相同的原因,按值传递 lamdas。

Is it alright to store the Controls by value in a vector this way

是的。

When I loop through the controls vector, should I be accessing them by value, or by reference

要么。尽管 Control 是一个很小的类,但我看不出有任何理由不按值访问。

关于c++ - 存储和传递 std::function - 按值还是按引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16990902/

相关文章:

c++ - 使用对象作为键时保持 std::map 平衡

c++ - C++ 中的原子操作

c++ - 最小化 Linux 共享库的依赖性

c++ - 如何创建用捕获的变量包装 lambda 的仿函数?

c++ - 使用字符串变量而不是字符串文字会导致错误

c++ - 编译类问题

c++ - 模块定义 (.def) 文件中的奇怪语法 - "?"和 "@"

c++ - 具有特定参数列表的函数指针

swift - 类型别名必须声明为公共(public),因为它符合公共(public)协议(protocol)中的要求

c++ - 类的非静态成员函数的函数指针