0

In C++ primer 5 ed. by Stanley lipmann chapter 15 OOP it is said:

std::multiset<std::shared_ptr<Quote>, decltype(compare)*> items{compare};

The elements in our multiset are shared_ptrs and there is no less-than operator for shared_ptr. As a result, we must provide our own comparison operation to order the elements (§11.2.2, p. 425). Here, we define a private static member, named compare, that compares the isbns of the objects to which the shared_ptrs point. We initialize our multiset to use this comparison function through an in-class initializer (§7.3.1, p. 274):"

But If I try this:

// a class that doesn't define < operator
struct A
{
    int x = 0;
};


int main()
{
    std::shared_ptr<A> pa(make_shared<A>());
    std::shared_ptr<A> pb(make_shared<A>());

    cout << (pb < pa) << endl; // 0

}
  • Why my code works although class A doesn't define less than operator?

  • The thing is that after checking cppreference about class std::shared_ptr I've found out that it has overloaded relational operators?!

  • I've also compiled the code against C++11 and still works fine!

  • So I'd like someone to explain to me that paragraph in the book. Thank you!

cigien
  • 57,834
  • 11
  • 73
  • 112
Maestro
  • 2,512
  • 9
  • 24
  • _there is no less-than operator for shared_ptr_... are you sure? – Mike Vine Aug 06 '20 at 23:32
  • 1
    https://en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmp – Mike Vine Aug 06 '20 at 23:32
  • 2
    Seems like the book is wrong if that's the exact quote. – Mike Vine Aug 06 '20 at 23:33
  • @MikeVine: It is not me who said that but in the book. – Maestro Aug 06 '20 at 23:38
  • 1
    Just checked that book on Amazon "Rewritten for the new C++11 Standard". Yikes - you ought to get a more uptodate book. See https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Mike Vine Aug 06 '20 at 23:40
  • 3
    It's working because it's not comparing the objects, it's comparing the pointers to the objects. From the link above Note that the comparison operators for shared_ptr simply compare pointer values; the actual objects pointed to are not compared. Having operator< defined for shared_ptr allows shared_ptrs to be used as keys in associative containers, like std::map and std::set. – Durstann Aug 06 '20 at 23:40

1 Answers1

2

Why my code works although class A doesn't define less than operator?

Because it is irrelevant what operators A have when the set doesn't contain elements of type A.

The set contains shared pointers.

The thing is that after checking cppreference about class std::shared_ptr I've found out that it has overloaded relational operators?!

Cppreference is correct.

So I'd like someone to explain to me that paragraph in the book.

The book is wrong.

eerorika
  • 232,697
  • 12
  • 197
  • 326