比较shared_ptr对象的相等性

时间:2015-11-11 12:52:19

标签: c++ c++11

是否有标准谓词来比较shared_ptr管理对象是否相等。

template<typename T, typename U>
inline bool target_equal(const T& lhs, const U& rhs)
{
    if(lhs && rhs)
    {
        return *lhs == *rhs;
    }
    else
    {
        return !lhs && !rhs;
    }
}

我想要类似于上面代码的东西,但如果已经有标准的解决方案,我会避免将其定义为自我。

2 个答案:

答案 0 :(得分:6)

不,没有这样的谓词。另一种方法是使用lambda函数 - 但你仍然需要自己定义它。

答案 1 :(得分:3)

不,没有标准的解决方案。 shared_ptr等的等于运算符仅比较指针而不是被管理对象。 你的解决方案很好。我建议这个版本检查指向的对象是否相同,如果其中一个共享指针为空,则返回false,另一个不是:

template<class T, class U>
bool compare_shared_ptr(const std::shared_ptr<T>&a,const std::shared_ptr<U>&b)
{
  if(a == b) return true;
  if(a && b) return *a == *b;
  return false;
}
相关问题