最佳答案
I was wondering how to properly check if an std::function is empty. Consider this example:
class Test {
std::function<void(int a)> eventFunc;
void registerEvent(std::function<void(int a)> e) {
eventFunc = e;
}
void doSomething() {
...
eventFunc(42);
}
};
This code compiles just fine in MSVC but if I call doSomething() without initializing the eventFunc the code obviously crashes. That's expected but I was wondering what is the value of the eventFunc? The debugger says 'empty'. So I fixed that using simple if statement:
void doSomething() {
...
if (eventFunc) {
eventFunc(42);
}
}
This works but I am still wondering what is the value of non-initialized std::function? I would like to write if (eventFunc != nullptr) but std::function is (obviously) not a pointer.
Why the pure if works? What's the magic behind it? And, is it the correct way how to check it?