std::shared_ptr<T>::owner_before
声明
template< class Y >
bool owner_before( const shared_ptr<Y>& other ) const noexcept;
template< class Y >
bool owner_before( const std::weak_ptr<Y>& other ) const noexcept;
检查此shared_ptr
是否在实现定义的、基于所有者的(相对于基于值的)顺序中先于另一个。该顺序是这样的:两个智能指针仅当它们都为空,或者它们都拥有同一个对象时才被视为相等,即使通过get()
获得的指针值不同(例如,因为它们指向同一对象内的不同子对象)。
此排序用于使 shared 指针和 weak 指针可用作关联容器的键,通常通过std::owner_less
。
参数
other
- 要比较的std::shared_ptr
或std::weak_ptr
。
返回值
如果*this
先于other
,则返回true
,否则返回false
。常见的实现会比较控制块的地址。
示例
#include <iostream>
#include <memory>
struct Foo {
int n1;
int n2;
Foo(int a, int b) : n1(a), n2(b) {}
};
int main()
{
auto p1 = std::make_shared<Foo>(1, 2);
std::shared_ptr<int> p2(p1, &p1->n1);
std::shared_ptr<int> p3(p1, &p1->n2);
std::cout
<< std::boolalpha
<< "p2 < p3 "
<< (p2 < p3) << '\n'
<< "p3 < p2 "
<< (p3 < p2) << '\n'
<< "p2.owner_before(p3) "
<< p2.owner_before(p3) << '\n'
<< "p3.owner_before(p2) "
<< p3.owner_before(p2) << '\n';
std::weak_ptr<int> w2(p2);
std::weak_ptr<int> w3(p3);
std::cout
// << "w2 < w3 " << (w2 < w3) << '\n' // won't compile
// << "w3 < w2 " << (w3 < w2) << '\n' // won't compile
<< "w2.owner_before(w3) "
<< w2.owner_before(w3) << '\n'
<< "w3.owner_before(w2) "
<< w3.owner_before(w2) << '\n';
}
结果
p2 < p3 true
p3 < p2 false
p2.owner_before(p3) false
p3.owner_before(p2) false
w2.owner_before(w3) false
w3.owner_before(w2) false