共享指针谓词;
Shared pointer predicate;
我真的很难理解这些声明
static bool compare ( const shared_ptr<int> lhs,const shared_ptr<int> rhs )
{ return (*lhs) < (*rhs) ; }
multiset<shared_ptr<int>,decltype(compare)*> item{ compare } ;
如果我不给指针后decltype(比较)它给出了错误?为什么错误?为什么我要提供bool*不是bool作为谓词像算法函数,再给比较在项目{比较}花括号的好处是什么?它会按排序顺序在multiset中插入对象吗?如果我没有给出{compare}会发生什么?
multiset
第二个参数期望的类型是谓词。这是对象c
的类型,使得c(lhs, rhs)
返回可转换为bool
的东西。
compare
和decltype(compare)
的类型是bool(shared_ptr<int>, shared_ptr<int>)
,一个函数类型。不能有函数类型的值,但是可以有指针和对函数类型的引用的值。这就是为什么这里需要*
。(实际上,有函数类型的值和那些你声明为函数的东西,但这些不能被创建,复制,除了调用它们和获取它们的地址之外,几乎什么都不能做。)总结:
decltype(compare)* ==> bool (*)(shared_ptr<int>, shared_ptr<int>)
是指向一个函数的指针,该函数按值接受两个shared_ptr<int>
,并返回一个bool
。然后,在multiset
构造函数中,为其提供该类型的值:
items{ compare }; // value
,或者更具体地说,是函数类型的值,该值将衰变为函数指针类型。让我们把它写得更明确:
items{ &compare }; // pointer to function compare
如果你没有给它任何东西,那么它将是一个空指针,当试图调用它进行比较时,你的应用程序将崩溃。
总之,您选择了一个非常复杂的案例来讨论(我已经跳过了一些我应该提到的内容)。这是一种更简单的方法:
struct shared_ptr_compare
{
bool operator()(std::shared_ptr<int> const& lhs, std::shared_ptr<int> const& rhs) const
{ return /*...*/; }
};
multiset<shared_ptr<int>, shared_ptr_compare> item; // no need to initialize
// shared_ptr_compare with anything, a default value will do just fine
注意:我删除了顶级const
修饰符,因为它对函数参数没有影响,它只向函数体发出不能更改值的信号。所以它确实有意义,但使解释类型变得复杂。
注释2:您应该将这些参数作为shared_ptr<int> const&
(与const shared_ptr<int>&
相同),因为您实际上不需要副本,并且这些副本必须保持引用计数器,这是一个必须在线程之间同步的操作。
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- std::condition_variable::wait()如何评估给定的谓词
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么指向非静态成员函数的指针不能用作标准库算法的一元谓词
- 在C++类中使用谓词函数指针
- std::list指针上排序算法的STL谓词
- STL:指针关联排序容器:排序谓词模板
- 共享指针谓词;