C++ 11 Lambda问题

nyk*_*kac 1 c++ lambda c++11

任何想法为什么以下代码段错误?

class foo代表任何阶级.这种接缝就像提供一个公平的界面一样好.

#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();
}
Run Code Online (Sandbox Code Playgroud)

ron*_*nag 6

它是segfauls因为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();
}
Run Code Online (Sandbox Code Playgroud)

例如

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();
}
Run Code Online (Sandbox Code Playgroud)