Compare equality of shared_ptr objects

Is there a standard predicate for comparing shared_ptr managed entities 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 code above, but I won’t define it myself if there is already a standard solution.

+5
source share
2 answers

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

+6
source

No, there is no standard solution. Equality operator shared_ptr, etc. compares only pointers, not managed objects. Your decision is in order. I suggest this version, which checks if the pointed object is the same, and returns false if one of the common pointers is null and the other 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; } 
+2
source

Source: https://habr.com/ru/post/1235697/


All Articles