比较shared_ptr对象的相等性

Jos*_*osé 7 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*řík 7

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


for*_*una 5

不,没有标准解决方案。shared_ptr等的相等运算符仅比较指针,而不比较托管对象。您的解决方案很好。我建议使用此版本来检查指向的对象是否相同,如果共享指针之一为null,而另一个则不是,则返回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;
}
Run Code Online (Sandbox Code Playgroud)