std::weak_ptr<T>::owner_before
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。
参数
other
- 要比较的 std::shared_ptr 或 std::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++ 标准。
DR | 应用于 | 发布时的行为 | 正确行为 |
---|---|---|---|
LWG 2873 | C++11 | owner_before 可能未声明为 noexcept | 已声明为 noexcept |
LWG 2942 | C++11 | LWG 2873 的解决方案中遗漏了 weak_ptr::owner_before | 已设为 noexcept |