I have the following two classes:
class A
{
public:
A() : value(false) {}
bool get() const
{
return value;
}
protected:
bool value;
};
class B : public A
{
public:
void set()
{
value = true;
}
};
Now I use them as follows:
B* b = new B;
std::shared_ptr<A> a(b);
auto func = std::bind(&B::set, *b);
std::cout << a->get() << std::endl;
func();
std::cout << a->get() << std::endl;
I expect a->get()
to return true
on the 2nd call, but func()
hasn't modified its value. Why is that?
std::bind
takes its paramters by value, so you are operating on copy of *b
.
You need to pass original object by std::ref
:
auto func = std::bind(&B::set, std::ref(*b));
Or simpler form would be just pass pointer to bind
:
auto func = std::bind(&B::set, b);