It segfauls because foobar
is not pointing to anything, you should use foo foobar;
.
EDIT:
A short review.
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();
}
e.g.
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();
}