【问题标题】:what is a 'valid' std::function?什么是“有效”的 std::function?
【发布时间】:2012-08-09 16:30:48
【问题描述】:

这里:

http://en.cppreference.com/w/cpp/utility/functional/function

operator bool 被描述为:“检查存储的可调用对象是否有效”。

可能默认构造的std::function 无效,但这是唯一的情况吗?

还有,它如何检查是否有效?

operator() 引发 std::bad_function_call 的情况是否正是对象无效的情况?

【问题讨论】:

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


    【解决方案1】:

    按原样写得不好,您的困惑是有道理的。 “有效”是指“有目标”。

    当一个std::function被分配一个函数时“有一个目标”:

    std::function<void()> x; // no target
    std::function<void()> y = some_void_function; // has target
    
    x = some_other_void_function; // has target
    y = nullptr; // no target
    
    x = y; // no target
    

    他们应该在使用之前定义“有效”,或者只是坚持使用官方措辞。

    【讨论】:

    • 好的,所以有效性检查只是类型检查,调用默认构造的std::function 正是引发std::bad_function_call 的情况,是吗?
    • @user710408:我不知道您所说的“有效性检查只是类型检查”是什么意思。有效性(现在假设定义“有一个目标”)在运行时确定,类型检查发生在编译时。只要函数无效(没有目标),就会发生错误的函数调用,无论是来自默认构造还是显式分配 nullptr
    • 我想我也不明白我的意思!谢谢:)
    • 这个答案正是我想要的,谢谢!
    【解决方案2】:

    语言标准说

    explicit operator bool() const noexcept;

    返回:如果 *this 有目标则返回 true,否则返回 false。

    意思是function 有什么可调用的。默认构造的function显然没有。

    【讨论】:

      猜你喜欢
      • 2019-04-26
      • 2015-07-18
      • 2015-01-20
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      相关资源
      最近更新 更多