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

前端之家收集整理的这篇文章主要介绍了c – 检查是否将std :: function分配给nullptr前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否有任何方法来检查您分配到std :: function的函数指针是否为nullptr.我期待着!-operator这样做,但它似乎只在函数被赋值为nullptr_t类型时才起作用.
  1. typedef int (* initModuleProc)(int);
  2.  
  3. initModuleProc pProc = nullptr;
  4. std::function<int (int)> m_pInit;
  5.  
  6. m_pInit = pProc;
  7. std::cout << !pProc << std::endl; // True
  8. std::cout << !m_pInit << std::endl; // False,even though it's clearly assigned a nullptr
  9. m_pInit = nullptr;
  10. std::cout << !m_pInit << std::endl; // True

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

  1. template<typename T>
  2. void AssignToFunction(std::function<T> &func,T* value)
  3. {
  4. if (value == nullptr)
  5. {
  6. func = nullptr;
  7. }
  8. else
  9. {
  10. func = value;
  11. }
  12. }

解决方法

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

猜你在找的C&C++相关文章