C++11 Lambda 问题

标签 c++ c++11 lambda

<分区>

知道为什么以下代码会出现段错误吗?

class foo 表示任何类。这似乎是提供事件接口(interface)的好主意。

#include <iostream>
#include <functional>

class foo
{
public:
  foo()
  {
    val = 42;  
  };

  void bar(std::function<int(foo*)> f)
  {
    this->_bar = std::bind(f, this);
  }
  std::function<int()> _bar;
  int val;
};

int main(void)
{
  foo *foobar;
  foobar->bar([](foo *self)->int{return self->val;});

  std::cout << foobar->_bar();
}

最佳答案

这是段错误,因为 foobar 没有指向任何东西,你应该使用 foo foobar;

编辑:

一个简短的评论。

class foo
{
public:
  foo()
  {
    val = 42;  // Use initialization list.
  };

  void bar(std::function<int(foo*)> f) // Use reference (foo&) instead of pointer (foo*).
  {
    this->_bar = std::bind(f, this); // Move "f" into bind and use "std::ref()" so you can pass "*this" by reference without copying.
  }

  // Hide local member variables

  std::function<int()> _bar; // Never use _ as a prefix, only the compiler is allowed to use _ prefix.
  int val;
};

int main(void)
{
  foo *foobar; // Use value semantics, i.e. "foo foobar".

  foobar->bar([](foo *self)->int{return self->val;});

  std::cout << foobar->_bar();
}

例如

class foo
{
public:
    foo()
        : val_(42)
    {
    };

    void set_bar(std::function<int(foo&)> f)
    {
        bar_ = std::bind(std::move(f), std::ref(*this));
    }

    int invoke_bar() const
    {   
        return bar_;
    }

    int get_val() const
    {
        return val_;
    }

private:

    std::function<int()> bar_;
    int val_;
};

int main(void)
{
  foo foobar;
  foobar.set_bar([](foo& self) -> int
  {
     return self.get_val();
  });

  std::cout << foobar.invoke_bar();
}

关于C++11 Lambda 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14039623/

相关文章:

C++(有点)工厂

c# - 从具有未知签名的 MethodInfo 创建表达式函数

c++ - 获取模板中数组最小值的函数

c++ - 在 C++ 中的文件(日志文件)中添加新行

c++ - 为什么只能从信号处理程序安全地调用异步信号安全函数?

lambda - Common Lisp 中的自执行 lambda 表达式

Java8 Lambda 表达式迭代枚举值并初始化最终成员

c++ - boost::polygon_90_data 无法处理面积值为 0 的多边形?

c++ - 在 C++11 中创建指针 vector 的惯用方法?

c++ - 摆脱丑陋的 C 结构