std::shared_ptr<T>:: owner_before
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Modifiers | ||||
| Observers | ||||
|
(C++17)
|
||||
|
(
until C++20*
)
|
||||
|
shared_ptr::owner_before
|
||||
|
(C++26)
|
||||
|
(C++26)
|
||||
| Non-member functions | ||||
|
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(C++20)
|
||||
|
functions
(
until C++26*
)
|
||||
| Helper classes | ||||
|
(C++20)
|
||||
| Deduction guides (C++17) |
|
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()
获取的指针值不同(例如因为它们指向同一对象内的不同子对象)。
此排序方式使得共享指针和弱指针可作为关联容器的键值使用,通常通过 std::owner_less 实现。
目录 |
参数
| 其他 | - | 待比较的 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)
|
提供基于所有者的共享指针和弱指针混合类型排序
(类模板) |