Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare shared_ptr object equality

Tags:

c++

c++11

Is there an standard predicate to compare shared_ptr managed objects for equality.

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;
    }
}

I want something similar to the above code, but will avoid defining it my self if there is already a standard solution.

like image 473
José Avatar asked Nov 11 '15 12:11

José


People also ask

What is the difference between shared_ptr and Weak_ptr?

The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.

What is the difference between shared_ptr and Unique_ptr?

In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

Why would you choose shared_ptr instead of Unique_ptr?

Use unique_ptr when if you want to have single ownership(Exclusive) of resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. Use shared_ptr if you want to share ownership of resource .

What does shared_ptr mean?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.


2 Answers

No, there isn't a standard solution. The equality operator of shared_ptr and the like compares only the pointers not the managed objects. Your solution is fine. I propose this version that checks if the pointed object is the same and returns false if one of the shared pointers is null and the other one it is not:

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;
}
like image 98
fortuna Avatar answered Oct 23 '22 04:10

fortuna


No, there isn't such a predicate. An alternative is to use lambda function - but you still need to define it yourself.

like image 7
Lukáš Bednařík Avatar answered Oct 23 '22 02:10

Lukáš Bednařík