共享指针谓词;

Shared pointer predicate;

本文关键字:谓词 指针 共享      更新时间:2023-10-16

我真的很难理解这些声明

        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 的东西

comparedecltype(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>&相同),因为您实际上不需要副本,并且这些副本必须保持引用计数器,这是一个必须在线程之间同步的操作。