如何正确检查std :: function在C ++ 11中是否为空? [英] How to properly check if std::function is empty in C++11?

查看:1836
本文介绍了如何正确检查std :: function在C ++ 11中是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何正确检查 std :: function 是否为空。考虑以下示例:

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);
    }
};

此代码在MSVC中可以很好地编译,但是如果我调用 doSomething()而不初始化 eventFunc 的代码显然会崩溃。这是预期的,但我想知道 eventFunc 的值是多少?调试器说。因此,我使用简单的if语句解决了该问题:

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);
        }
   }

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

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.

为什么纯正if起作用?它背后的魔力是什么?而且,这是检查它的正确方法吗?

Why the pure if works? What's the magic behind it? And, is it the correct way how to check it?

推荐答案

您不是要检查空的lambda,而是 std :: function 有一个可调用的目标存储在其中。由于 std :: function ::,检查是明确定义的并且有效运算符bool 允许在需要布尔值的上下文中(例如<$中的条件表达式)隐式转换为 bool c $ c> if 语句。)

You're not checking for an empty lambda, but whether the std::function has a callable target stored in it. The check is well-defined and works because of std::function::operator bool which allows for implicit conversion to bool in contexts where boolean values are required (such as the conditional expression in an if statement).

此外,空lambda 的概念并没有真正使感。在后台,编译器将lambda表达式转换为 struct (或 class )定义,并将捕获的变量存储作为此结构的数据成员。还定义了一个公共函数调用运算符,它使您可以调用lambda。那么空的lambda是什么呢?

Besides, the notion of an empty lambda doesn't really make sense. Behind the scenes the compiler converts a lambda expression into a struct (or class) definition, with the variables you capture stored as data members of this struct. A public function call operator is also defined, which is what allows you to invoke the lambda. So what would an empty lambda be?

您还可以编写 if(eventFunc!= nullptr )(如果需要),它等同于问题中的代码。 std :: function 定义 operator == operator!= 重载以与 nullptr_t

You can also write if(eventFunc != nullptr) if you wish to, it's equivalent to the code you have in the question. std::function defines operator== and operator!= overloads for comparing with a nullptr_t.

这篇关于如何正确检查std :: function在C ++ 11中是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆