将 boost intrusive_ptr 与不同 const-ness 进行比较

问题描述 投票:0回答:1

我想将

boost::intrusive_ptr
实例与基础类型的不同常量进行比较,但不幸的是,如果您取消注释该行,则它不起作用

#include <boost/intrusive_ptr.hpp>
#include <memory>

struct S {};

void intrusive_ptr_release(const S*){}

int main() { 

    boost::intrusive_ptr<const S> boost_const_ptr;
    boost::intrusive_ptr<S> boost_ptr;
    // if(boost_const_ptr < boost_ptr) {} // <------ here
    
    const S* s_const_ptr;
    S* s_ptr;
    if(s_const_ptr < s_ptr) {}

    std::unique_ptr<const S> u_const_ptr;
    std::unique_ptr<S> u_ptr;
    if(u_const_ptr < u_ptr) {}
}

错误将是:

no match for 'operator<' (operand types are 'boost::intrusive_ptr<const S>' and 'boost::intrusive_ptr<S>')

我可以比较原始指针,甚至可以比较

std::unique_ptr
,但不能比较
boost::intrusive_ptr
。这是有原因的,还是只是疏忽?

c++ pointers boost constants smart-pointers
1个回答
0
投票

一个可能的原因是,与

shared_ptr
< would be impossible in general. Other smart pointer types don't have to deal with the possibility of heterogenous comparison1 具有相同的语义,但
shared_ptr
weak_ptr
intrusive_ptr
可以。

template<class T, class U>
bool operator<(shared_ptr<T> const & a, shared_ptr<U> const & b) noexcept;

退货:

未指定的值使得

  • operator<
    是严格的弱排序,如 C++ 标准的 [lib.alg.sorting] 部分所述;

  • operator<
    !(a < b) && !(b < a)
    定义的等价关系下,两个shared_ptr实例是等价的当且仅当它们 共有所有权或两者都是空的。

shared_ptr
可以通过比较引用计数的地址来做到这一点。
intrusive_ptr
不能这样做,因为它没有对引用计数的指针访问。

  1. 例如当您将
    shared_ptr<Base>
    shared_ptr<Derived>
    进行比较时,它们可能共享同一对象的所有权,这对于
    unique_ptr<Base>
    unique_ptr<Derived>
    来说是不可能的。
© www.soinside.com 2019 - 2024. All rights reserved.