C++ 共享指针谓词;
我真的很难理解这些宣言C++ 共享指针谓词;,c++,shared-ptr,decltype,multiset,C++,Shared Ptr,Decltype,Multiset,我真的很难理解这些宣言 static bool compare ( const shared_ptr<int> lhs,const shared_ptr<int> rhs ) { return (*lhs) < (*rhs) ; } multiset<shared_ptr<int>,decltype(compare)*> item{ compare } ; 静态布尔比较
static bool compare ( const shared_ptr<int> lhs,const shared_ptr<int> rhs )
{ return (*lhs) < (*rhs) ; }
multiset<shared_ptr<int>,decltype(compare)*> item{ compare } ;
静态布尔比较(常数共享\u ptr lhs、常数共享\u ptr rhs)
{返回(*lhs)<(*rhs);}
多集项{compare};
如果我在decltype(compare)之后没有给出指针,它会给出错误吗?为什么会出错?为什么我应该提供bool*而不是bool作为类似谓词的算法函数,同样,在{compare}项中用花括号进行比较有什么好处?它会按排序顺序在multiset中插入对象吗?如果我没有给出{compare},会发生什么?第二个参数所期望的类型是谓词。这是对象
c
的类型,使得c(lhs,rhs)
返回可转换为bool
的对象
compare
和decltype(compare)
的类型是bool(shared_ptr,shared_ptr)
,一种函数类型。不能有函数类型的值,但可以有指向函数类型的指针和引用的值。这就是为什么您需要那里的*
。(实际上,有函数类型的值,也有您声明为函数的值,但是除了调用它们并获取它们的地址之外,这些值不能被创建、复制,也不能做任何事情。)总结:
decltype(compare)* ==> bool (*)(shared_ptr<int>, shared_ptr<int>)
或者更具体地说,函数类型的值将衰减为函数指针类型。所以让我们明确地说:
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
struct shared\u ptr\u compare
{
布尔运算符()(std::shared_ptr const&lhs,std::shared_ptr const&rhs)const
{return/*…*/;}
};
多集项;//不需要初始化
//shared_ptr_与任何东西相比,默认值都可以
注意:我删除了顶级的常量
修饰符,因为它对函数参数没有影响,它只向函数体发出不能更改值的信号。所以它确实有意义,但会使解释类型变得复杂
注意2:您应该将这些参数作为
共享的\u ptr const&
(与共享的\u ptr&
相同),因为您实际上不需要副本,而且这些副本必须保留一个引用计数器,这是一个必须在线程之间同步的操作。提示:decltype(compare)
不是调用compare
的返回类型。compare的返回类型是bool,不是吗?但是compare
的类型与其返回类型不同。为什么????我的知识真的很少。。请解释一下。好的,compare
是一种返回bool的特定类型的静态函数decltype(compare)
是该函数的类型item
是一个使用compare
作为比较函数创建的multimap
,以实现其元素的排序。如果声明是这样的呢。。多集项目;这不是也会有序地插入元素吗?@TamimAdDari它会根据不同的顺序插入元素:指针值,而不是指针指向的值。
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