Namespaces
Variants

std::weak_ptr<T>:: owner_before

From cppreference.net

Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
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() によって取得されたポインタの値が異なる場合(例えば、同じオブジェクト内の異なるサブオブジェクトを指している場合)でも同様です。

この順序付けは、共有ポインタおよび弱ポインタを連想コンテナのキーとして使用できるようにするために用いられます。通常は std::owner_less を通じて実現されます。

目次

パラメータ

other - 比較対象の std::shared_ptr または std::weak_ptr

戻り値

true * this other に先行する場合、 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' // コンパイル不可
//            << "w3 < w2 " << (w3 < w2) << '\n' // コンパイル不可
              << "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 2083 C++11 owner_before が宣言されていなかった const 宣言された const
LWG 2942 C++11 owner_before が宣言されていなかった noexcept 宣言された noexcept

関連項目

(C++11)
sharedポインタとweakポインタの混合型所有者ベースの順序付けを提供する
(クラステンプレート)