如何在C ++ 11中正确检查std :: function是否为空?

时间:2014-02-16 02:44:01

标签: c++ c++11 std-function

我想知道如何正确检查std::function是否为空。考虑这个例子:

class Test {
    std::function<void(int a)> eventFunc;

    void registerEvent(std::function<void(int a)> e) {
        eventFunc = e;
    }

    void doSomething() {
        ...
        eventFunc(42);
    }
};

此代码在MSVC中编译得很好但是如果我在没有初始化doSomething()的情况下调用eventFunc,代码显然会崩溃。这是预期的,但我想知道eventFunc的价值是多少?调试器说'empty'。所以我使用简单的if语句修复了它:

   void doSomething() {
        ...
        if (eventFunc) {
            eventFunc(42);
        }
   }

这有效,但我仍然想知道未初始化std::function的价值是多少?我想写if (eventFunc != nullptr),但std::function(显然)不是指针。

为什么纯净如果有效?它背后的魔力是什么?而且,这是检查它的正确方法吗?

3 个答案:

答案 0 :(得分:89)

您没有检查空的lambda,但是std::function是否有一个可调用的目标存储在其中。检查是明确定义的,因为std::function::operator bool允许在需要布尔值的上下文中隐式转换为bool(例如if语句中的条件表达式)。 / p>

此外,空lambda 的概念并不真正有意义。在后台,编译器将lambda表达式转换为struct(或class)定义,并将捕获的变量存储为此struct的数据成员。还定义了一个公共函数调用操作符,它允许您调用lambda。那么一个空的lambda会是什么?


如果您愿意,也可以写if(eventFunc != nullptr),它等同于您在问题中的代码。 std::function defines operator==operator!=重载与nullptr_t进行比较。

答案 1 :(得分:19)

点击此处http://www.cplusplus.com/reference/functional/function/operator_bool/

示例

// function::operator bool example
#include <iostream>     // std::cout
#include <functional>   // std::function, std::plus

int main () {
  std::function<int(int,int)> foo,bar;
  foo = std::plus<int>();

  foo.swap(bar);

  std::cout << "foo is " << (foo ? "callable" : "not callable") << ".\n";
  std::cout << "bar is " << (bar ? "callable" : "not callable") << ".\n";

  return 0;
}

<强>输出

  

foo不可调用。

     

bar可以调用。

答案 2 :(得分:-1)

(让我提供一个明确的答案。)

您可以检查std::function::operator boolstd::function是否为空。

  

true:如果对象可调用。
  false:否则(对象是一个空函数)

示例

#include <iostream>
#include <functional>

int main ()
{
    std::function<int(int,int)> foo = std::plus<int>();//assigned: not empty
    std::function<int(int,int)> bar;//not assigned: empty

    std::cout << "foo is " << (foo ? "not empty" : "empty") << ".\n";
    std::cout << "bar is " << (bar ? "not empty" : "empty") << ".\n";

    return 0;
}

输出

  

foo不为空。
  栏为空。