In comments under another question, it was stated that a common mistake is to:
invoke
std::functionwhen calling it leads to destruction of object which holds it
While clearly a "dangerous" thing to do that would be avoided in robust code, is it actually wrong? I cannot find any wording in the standard that ensures:
- A
std::functionmust not be destroyed by its target callable - A
std::function's lifetime must not end during execution of its target callable - The lifetime of a functor in general must not end during its execution
To my knowledge, it is legal and well-defined (though in poor taste) to do things like the following:
struct Foo
{
void baz()
{
delete this;
// Just don't use any members after this point
}
};
int main()
{
Foo* foo = new Foo();
foo->baz();
}
This suggests that, in the absence of any overriding restrictions, none of which I can find, the following would also be technically well-defined:
#include <functional>
struct Bar
{
std::function<void()> func;
};
int main()
{
Bar* bar = new Bar();
bar->func = [&]() { delete bar; };
bar->func();
}
Is this not the case? If not, which wording prohibits it?
(For bonus points, it would be interesting if this has changed since previous standards.)