std::weak_ptr<T>::owner_before
提供: cppreference.com
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 より前に来るかどうかを調べます。 この順序は、2つのスマートポインタがどちらも空であるか、同じオブジェクトを所有していれば、 get() によって取得されるポインタの値が異なっていても (例えば同じオブジェクトの別々のサブオブジェクトを指しているなど)、それらは等しいものとして比較されます。
この順序付けは、 shared_ptr や weak_ptr を連想コンテナのキーとして使用可能とするために、一般的には std::owner_less を通して、使用されます。
引数
| other | - | 比較する std::shared_ptr または std::weak_ptr |
戻り値
*this が other より前に来るならば true、そうでなければ false。 一般的な実装では制御ブロックのアドレスが比較されます。
例
Run this code
#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 might not be declared noexcept
|
declared noexcept |
| LWG 2942 | C++11 | weak_ptr::owner_before is missed in LWG 2873's resolution
|
made noexcept |
関連項目
(C++11) |
shared_ptr と weak_ptr の混ざった型に対するオーナーベースの順序付けを提供します (クラステンプレート) |