名稱空間
變體
操作

std::shared_ptr<T>::owner_before

來自 cppreference.com
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(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() 獲得指標的值不同(例如因為它們指向同一物件中的不同子物件)。

此順序用於使得 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 2873 C++11 owner_before 未被宣告為 noexcept 宣告為 noexcept

[編輯] 參閱

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