std::shared_ptr<T>::owner_before
来自cppreference.com
< cpp | memory | shared ptr
template<class Y > bool owner_before(const shared_ptr<Y>& other )constnoexcept; | ||
template<class Y > bool owner_before(conststd::weak_ptr<Y>& other )constnoexcept; | ||
以实现定义的基于拥有者(与基于值相反)顺序,检查此 shared_ptr
是否先于 other。两个智能指针仅若都拥有同一对象或均为空才比较相等,即使由 get() 获得的指针不同(例如因为它们指向同一对象中的不同子对象)也是如此。
这种顺序用于令共享和弱指针可用作关联容器中的键,通常经由 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' // 无法编译// << "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++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2873 | C++11 | owner_before 未声明为 noexcept | 声明为 noexcept |
[编辑]参阅
(C++11) | 提供共享指针和弱指针的基于所有者的混合类型排序 (类模板) |