命名空间
变体
操作

std::shared_ptr<T>::owner_before

来自 cppreference.cn
< cpp‎ | memory‎ | shared ptr
 
 
内存管理库
(仅为解释目的*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
 
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 是否先于 other 在实现定义的基于所有者(而非基于值)的顺序中。此顺序使得只有当两个智能指针都为空,或者它们都拥有同一对象时,它们才比较相等,即使通过 get() 获得的指针值不同(例如,因为它们指向同一对象内不同的子对象)。

此排序用于使共享指针和弱指针可用作关联容器中的键,通常通过 std::owner_less

目录

[编辑] 参数

other - 要比较的 std::shared_ptrstd::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

[编辑] 缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 2873 C++11 owner_before 未声明为 noexcept 声明为 noexcept

[编辑] 参见

提供共享指针和弱指针的混合类型基于所有者的排序
(类模板) [编辑]