C++ 入门第 5 版。 shared_ptr 和关联容器
C++ primer 5 ed. shared_ptr and associative containers
C++ 入门第 5 版。 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. 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):"
但如果我尝试这样做:
// 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
}
尽管 class A
没有定义小于运算符,但为什么我的代码仍然有效?
问题是,在检查了关于 class std::shared_ptr
的 cppreference 之后,我发现它已经重载了关系运算符?!
我还针对 C++11 编译了代码并且仍然可以正常工作!
所以我希望有人给我解释一下书中的那一段。谢谢!
Why my code works although class A doesn't define less than operator?
因为当集合不包含 A
.
类型的元素时,运算符 A
的内容无关紧要
该集合包含共享指针。
The thing is that after checking cppreference about class std::shared_ptr I've found out that it has overloaded relational operators?!
Cppreference 正确。
So I'd like someone to explain to me that paragraph in the book.
书错了。
C++ 入门第 5 版。 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. 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):"
但如果我尝试这样做:
// 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
}
尽管 class
A
没有定义小于运算符,但为什么我的代码仍然有效?问题是,在检查了关于
class std::shared_ptr
的 cppreference 之后,我发现它已经重载了关系运算符?!我还针对 C++11 编译了代码并且仍然可以正常工作!
所以我希望有人给我解释一下书中的那一段。谢谢!
Why my code works although class A doesn't define less than operator?
因为当集合不包含 A
.
A
的内容无关紧要
该集合包含共享指针。
The thing is that after checking cppreference about class std::shared_ptr I've found out that it has overloaded relational operators?!
Cppreference 正确。
So I'd like someone to explain to me that paragraph in the book.
书错了。