这可能是一个哲学问题,但我遇到了以下问题:
如果你定义了一个 std::function,但你没有正确初始化它,你的应用程序将会崩溃,像这样:
typedef std::function<void(void)> MyFunctionType;
MyFunctionType myFunction;
myFunction();
如果函数作为参数传递,如下所示:
void DoSomething (MyFunctionType myFunction)
{
myFunction();
}
然后,当然,它也会崩溃。这意味着我被迫添加这样的检查代码:
void DoSomething (MyFunctionType myFunction)
{
if (!myFunction) return;
myFunction();
}
要求这些检查让我回想起过去的 C 时代,您还必须明确检查所有指针参数:
void DoSomething (Car *car, Person *person)
{
if (!car) return; // In real applications, this would be an assert of course
if (!person) return; // In real applications, this would be an assert of course
...
}
幸运的是,我们可以在 C++ 中使用引用,这使我无法编写这些检查(假设调用者没有将 nullptr 的内容传递给函数:
void DoSomething (Car &car, Person &person)
{
// I can assume that car and person are valid
}
那么,为什么 std::function 实例有默认构造函数呢?如果没有默认构造函数,您就不必添加检查,就像函数的其他普通参数一样。在那些你想传递“可选”std::function 的“罕见”情况下,你仍然可以传递一个指向它的指针(或使用 boost::optional)。