In comments under another question, it was stated that a common mistake is to:
invoke
std::function
when 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::function
must 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.)
if (self_destruct) delete this;
which seems same-ish. Also seems to be in poor taste, but I hope legal because there is a lot of it in my project's codebase.bool
because the standard doesn't tell us whether or not we can do so while eating pasta. If, as the programmer, you meet all the preconditions of a function call, then you should be able to expect a well-defined result. And, from my reading of the linked passages, that's all this hypothetical terrible programmer is doing.