Can I delete a std::function
object from within the function being called by its operator()
? Like this:
#include <functional>
#include <iostream>
int main() {
std::function<void()>* fn = nullptr;
fn = new std::function<void()>([&fn](){
std::cout << "In my lambda\n";
delete fn; // Is this undefined behaviour?
// fn = nullptr; // This definitely *is* undefined behviour!
});
(*fn)(); // Call lambda
return 0;
}
This is a very stripped down version of the true situation. The real code smart pointers rather than explicit new
and delete
(of course), and really the function is removing itself from an STL data structure.
I am interested in two questions:
- Is this definitely not undefined behaviour according to the C++ standard?
- Do implementations allow this in practice? Even if this is allowed in theory, if it's such an unusual edge case that implementations may crash in practice then I still want to avoid it!
Similar questions that have been asked before:
- This is similar to the many questions about
delete this
(e.g. Is delete this allowed). This question is different though because it depends on the library part of the standard as well as the language: ifstd::function
is allowed to access any member variables after it calls its contained function then this is undefined behaviour. - There are one or two questions that are more similar to this one (e.g. std::function delete-itself when during its call?) but they seem to be interested in, roughly speaking, whether it's probably going to be alright in their application rather than whether the C++ standard specifically allows it. Certainly none of the answers I've seen have mentioned the C++ standard for
std::function
.