相关疑难解决方法(0)

为什么std :: function实例有一个默认的构造函数?

这可能是一个哲学问题,但我遇到了以下问题:

如果您定义了一个std :: function,并且没有正确初始化它,那么您的应用程序将崩溃,如下所示:

typedef std::function<void(void)> MyFunctionType;
MyFunctionType myFunction;
myFunction();
Run Code Online (Sandbox Code Playgroud)

如果函数作为参数传递,如下所示:

void DoSomething (MyFunctionType myFunction)
   {
   myFunction();
   }
Run Code Online (Sandbox Code Playgroud)

然后,当然,它也崩溃了.这意味着我被迫添加这样的检查代码:

void DoSomething (MyFunctionType myFunction)
   {
   if (!myFunction) return;
   myFunction();
   }
Run Code Online (Sandbox Code Playgroud)

需要这些检查让我回到旧的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
   ...
   }
Run Code Online (Sandbox Code Playgroud)

幸运的是,我们可以在C++中使用引用,这阻止我编写这些检查(假设调用者没有将nullptr的内容传递给函数:

void DoSomething (Car &car, Person &person)
   {
   // I can assume that …
Run Code Online (Sandbox Code Playgroud)

c++ std-function

13
推荐指数
4
解决办法
1万
查看次数

标签 统计

c++ ×1

std-function ×1