C++ 那些被遗漏的细节6 shared_ptr owner_before

本文详细介绍了C++中shared_ptr和weak_ptr的owner_before函数,该函数用于基于所有权的排序,使得智能指针可以作为关联容器的键。通过示例展示了其用法和返回结果,强调了即使指向不同子对象,只要拥有相同对象,比较结果仍相等。
摘要由CSDN通过智能技术生成
语法
// <memory>
// template< class T > class shared_ptr; (since C++11)
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;
简述
  • Checks whether this shared_ptr precedes other in implementation defined owner-based (as opposed to value-based) order. The order is such that two smart pointers compare equivalent only if they are both empty or if they both own the same object, even if the values of the pointers obtained by get() are different (e.g. because they point at different subobjects within the same object)
  • This ordering is used to make shared and weak pointers usable as keys in associative containers, typically through std::owner_less.(用途:排序用,使shared_ptr或weak_ptr能作为关联容器的key)
例子
#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
参考
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值