Is the behavior of the following code well defined? How does the f()
call behave?
#include <functional>
#include <iostream>
struct A
{
void shout()
{
std::cout <<"shout";
}
};
int main()
{
std::function<void()> f;
{
A a;
f = std::bind(&A::shout, &a);
}
f(); // what happens here?
}
Your code ends up storing a dangling reference (to an object that no longer exists) inside the function wrapper, and invoking the function results in undefined behaviour.
If the original object doesn't live as long as the wrapper, you can always store a copy of the object in the wrapper:
f = std::bind(&A::shout, a);
// ^^^ copy