简体   繁体   English

C++ 底漆 5 版。 shared_ptr 和关联容器

[英]C++ primer 5 ed. shared_ptr and associative containers

In C++ primer 5 ed.在 C++ 引物 5 版中。 by Stanley lipmann chapter 15 OOP it is said: Stanley lipmann 第 15 章 OOP 说:

 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.我们的多重集中的元素是 shared_ptrs 并且 shared_ptr 没有小于运算符。 As a result, we must provide our own comparison operation to order the elements (§11.2.2, p. 425).因此,我们必须提供自己的比较操作来对元素进行排序(第 11.2.2 节,第 425 页)。 Here, we define a private static member, named compare, that compares the isbns of the objects to which the shared_ptrs point.在这里,我们定义了一个名为 compare 的私有 static 成员,它比较 shared_ptrs 指向的对象的 isbns。 We initialize our multiset to use this comparison function through an in-class initializer (§7.3.1, p. 274):"我们通过类内初始化器(§7.3.1,第 274 页)初始化我们的多重集以使用此比较 function:“

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?为什么我的代码有效,尽管 class A没有定义小于运算符?

  • The thing is that after checking cppreference about class std::shared_ptr I've found out that it has overloaded relational operators?!问题是,在检查了关于class std::shared_ptr的 cppreference 之后,我发现它已经重载了关系运算符?!

  • I've also compiled the code against C++11 and still works fine!我还针对 C++11 编译了代码,并且仍然可以正常工作!

  • So I'd like someone to explain to me that paragraph in the book.所以我希望有人向我解释书中的那一段。 Thank you!谢谢!

Why my code works although class A doesn't define less than operator?为什么我的代码有效,尽管 class A 没有定义小于运算符?

Because it is irrelevant what operators A have when the set doesn't contain elements of type A .因为当集合不包含类型A元素时,运算符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?!问题是,在检查了关于 class std::shared_ptr 的 cppreference 之后,我发现它已经重载了关系运算符?!

Cppreference is correct. Cppreference 是正确的。

So I'd like someone to explain to me that paragraph in the book.所以我希望有人向我解释书中的那一段。

The book is wrong.书错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM