std::shared_ptr::owner_before

From Cppreference

Jump to: navigation, search
template< class T >
bool owner_before( const shared_ptr<T>& other) const;

template< class T >
bool owner_before( const std::weak_ptr<T>& other) const;

Checks whether this shared_ptr precedes other in implementation defined owner-based (as opposed to value-based) order. The order is such that two smart pointers compare equivalent only if they are both empty or if they both own the same object, even if the values of the pointers obtained by get() are different (e.g. because they point at different subobjects within the same object)

This ordering is used to make shared and weak pointers usable as keys in associative containers, typically through std::owner_less.

Contents

[edit] Parameters

other - the std::shared_ptr or std::weak_ptr to be compared

[edit] Return value

true if *this precedes other, false otherwise. Common implementations compare the addresses of the control blocks.

[edit] Example

#include <memory>
#include <iostream>
 
struct B1 { int n1;};
struct B2 { int n2;};
struct D : B1, B2 {};
int main()
{
    auto p1 = std::make_shared<D>();
    std::shared_ptr<void> p2 = std::static_pointer_cast<B2>(p1);
    std::cout << std::boolalpha
              << "p1<p2 " << (p1 < p2) << '\n'
              << "p2<p1 " << (p2 < p1) << '\n'
              << "p1.owner_before(p2) " << p1.owner_before(p2) << '\n'
              << "p2.owner_before(p1) " << p2.owner_before(p1) << '\n';
}

Output:

p1<p2 true
p2<p1 false
p1.owner_before(p2) false
p2.owner_before(p1) false

[edit] See also

owner_less (C++11)
provides mixed-type ownership-based ordering of shared and weak pointesr
(class template)