> what is the reason for providing relational operators '<', '>' for unique_ptr ?
The relational operators (<, > etc.) for smart pointers are more involved than the same operators for normal object pointers. Unlike the relational operators for built-in pointers, which only impose a partial ordering, these operators for smart pointers are required to impose a total ordering.
For example, for operator<:
template<class T1, class D1, class T2, class D2>
bool operator<(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y);
#Requires: Let CT denote
common_type_t<typename unique_ptr<T1, D1>::pointer, typename unique_ptr<T2, D2>::pointer>
Then the specialization less<CT> shall be a function object type that induces a strict weak ordering on the pointer values.
It's a bit unfortunate that the < operator defines the default sort order. It often makes sense to be able to sort objects in some consistent order, but the relational operators doesn't really make much sense for most types.
Thanks JLBorges and Peter87 for providing your feedback :)
I have some further clarifications :
JLBorges wrote:
vector<unique_ptr<base>> sorted_vec;
vector<unique_ptr<base>>::iterator i = lower_bound(sorted_vec.begin(), sorted_vec.end(), d); [1]
For [1] to be successful, sorted_vec must be sorted that justifies the need for providing '<' operator.
But on what basis is this sorting done ?
[a] On the basis of value that we get from .get() ; i.e. the address of object pointed by the unique_ptr
[b] On the basis of value pointed by the unique_ptr, i.e. on the basis of *(.get()) ?
[c] If it is on the basis of [a], then I wonder why would we want to sort the pointer array on the basis of the address of the objects they point to ?
The comparison is done based on the value returned by get() (the address of the managed object).
(Note that the deleter does not participate in these comparisons.)
> why would we want to sort the pointer array on the basis of the address of the objects they point to ?
I can't think of a very good use case for sorting a sequence of unique pointers.
My reply (the one you ignored) was probably the most useful, if you would just take the time to think about it.
JLBorges initial reply basically just said that unique_ptr's must be unique.
Mine was asking "what is the use in the built-in case"?
Yes.
umm... I also cant think of any use-case why would storing them in an ordered container make sense. Maybe to ensure that containers can store unique_ptr's as well ?