加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 检查是否将std :: function分配给nullptr

发布时间:2020-12-16 05:00:40 所属栏目:百科 来源:网络整理
导读:我想知道是否有任何方法来检查您分配到std :: function的函数指针是否为nullptr.我期待着!-operator这样做,但它似乎只在函数被赋值为nullptr_t类型时才起作用. typedef int (* initModuleProc)(int);initModuleProc pProc = nullptr;std::functionint (int)
我想知道是否有任何方法来检查您分配到std :: function的函数指针是否为nullptr.我期待着!-operator这样做,但它似乎只在函数被赋值为nullptr_t类型时才起作用.
typedef int (* initModuleProc)(int);

initModuleProc pProc = nullptr;
std::function<int (int)> m_pInit;

m_pInit = pProc;
std::cout << !pProc << std::endl;   // True
std::cout << !m_pInit << std::endl; // False,even though it's clearly assigned a nullptr
m_pInit = nullptr;
std::cout << !m_pInit << std::endl; // True

我写了这个辅助函数来解决这个问题.

template<typename T>
void AssignToFunction(std::function<T> &func,T* value)
{
    if (value == nullptr)
    {
        func = nullptr;
    }
    else
    {
        func = value;
    }
}

解决方法

这是你的std :: function实现中的一个错误(也很明显是我的),标准说运算符!如果对象是用null函数指针构造的,则返回true,参见[func.wrap.func]段落8.赋值运算符应该等同于用参数构造std :: function并交换它,所以运算符!在这种情况下也应该返回true.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读