名稱空間
變體
操作

std::weak_ptr<T>::owner_before

來自 cppreference.com
< 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

[編輯] 參閱

提供基於所有者的共享指標和弱指標的混合型別排序
(類模板) [編輯]