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.
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.
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.
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 .
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.
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;
}
No, there isn't such a predicate. An alternative is to use lambda function - but you still need to define it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With