命名空间
变体
操作

std::weak_ptr<T>::owner_before

来自 cppreference.cn
< cpp‎ | 内存‎ | weak 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 weak_ptr<Y>& other ) const noexcept;
template< class Y >
bool owner_before( const std::shared_ptr<Y>& other ) const noexcept;

检查此 weak_ptr 在实现定义的基于所有者(而不是基于值)的顺序中是否先于 other。此顺序使得只有当两个智能指针都为空或它们都拥有相同的对象时,它们才被视为等效,即使通过 get() 获取的指针值不同(例如,因为它们指向同一对象内不同的子对象)。

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

目录

[编辑] 参数

其他 - 要比较的 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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 2083 C++11 owner_before 未声明为 const 声明为 const
LWG 2942 C++11 owner_before 未声明为 noexcept 声明为 noexcept

[编辑] 参阅

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