Spec-Zone.ru › C++

operator==, !=, <, <=, >, >=, <=> (std::shared_ptr)

Определено в заголовочном файле <memory>
Сравнение двух объектов shared_ptr.
template< class T, class U > 
bool operator==( const std::shared_ptr<T>& lhs,
                 const std::shared_ptr<U>& rhs ) noexcept;
(1) (с C++11)
template< class T, class U > 
bool operator!=( const std::shared_ptr<T>& lhs,
                 const std::shared_ptr<U>& rhs ) noexcept;
(2) (с C++11)
(до C++20)
template< class T, class U > 
bool operator<( const std::shared_ptr<T>& lhs,
                const std::shared_ptr<U>& rhs ) noexcept;
(3) (с C++11)
(до C++20)
template< class T, class U > 
bool operator>( const std::shared_ptr<T>& lhs,
                const std::shared_ptr<U>& rhs ) noexcept;
(4) (с C++11)
(до C++20)
template< class T, class U > 
bool operator<=( const std::shared_ptr<T>& lhs,
                 const std::shared_ptr<U>& rhs ) noexcept;
(5) (с C++11)
(до C++20)
template< class T, class U > 
bool operator>=( const std::shared_ptr<T>& lhs,
                 const std::shared_ptr<U>& rhs ) noexcept;
(6) (с C++11)
(до C++20)
template< class T, class U > 
std::strong_ordering operator<=>( const std::shared_ptr<T>& lhs,
                                  const std::shared_ptr<U>& rhs ) noexcept;
(7) (с C++20)
Сравнение объекта shared_ptr с указателем на ноль.
template< class T > 
bool operator==( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
(8) (с C++11)
template< class T >
bool operator==( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
(9) (с C++11)
(до C++20)
template< class T >
bool operator!=( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
(10) (с C++11)
(до C++20)
template< class T >
bool operator!=( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
(11) (с C++11)
(до C++20)
template< class T >
bool operator<( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
(12) (с C++11)
(до C++20)
template< class T >
bool operator<( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
(13) (с C++11)
(до C++20)
template< class T >
bool operator>( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
(14) (с C++11)
(до C++20)
template< class T >
bool operator>( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
(15) (с C++11)
(до C++20)
template< class T >
bool operator<=( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
(16) (с C++11)
(до C++20)
template< class T >
bool operator<=( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
(17) (с C++11)
(до C++20)
template< class T >
bool operator>=( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;
(18) (с C++11)
(до C++20)
template< class T >
bool operator>=( std::nullptr_t, const std::shared_ptr<T>& rhs ) noexcept;
(19) (с C++11)
(до C++20)
template< class T >
std::strong_ordering operator<=>( const std::shared_ptr<T>& lhs,
                                  std::nullptr_t ) noexcept;
(20) (с C++20)

Сравнивает два объекта shared_ptr<T> или сравнивает shared_ptr<T> с указателем на ноль.

Обратите внимание, что операторы сравнения для shared_ptr просто сравнивают значения указателей; сами объекты, на которые они указывают, не сравниваются. Определение операторов сравнения для shared_ptr позволяет использовать shared_ptr в качестве ключей в ассоциативных контейнерах, таких как std::map и std::set.

Операторы <, <=, >, >=, и != синтезируются из оператора<=> и оператора== соответственно.

(с C++20)

Параметры

lhs - левое значение для сравнения
rhs - правое значение для сравнения

Возвращаемое значение

1) lhs.get() == rhs.get()
2) !(lhs == rhs)
3) std::less<V>()(lhs.get(), rhs.get()), где V — сложный тип указателя std::shared_ptr<T>::element_type* и std::shared_ptr<U>::element_type*.
4) rhs < lhs
5) !(rhs < lhs)
6) !(lhs < rhs)
7) std::compare_three_way{}(x.get(), y.get())
8) !lhs
9) !rhs
10) (bool)lhs
11) (bool)rhs
12) std::less<std::shared_ptr<T>::element_type*>()(lhs.get(), nullptr)
13) std::less<std::shared_ptr<T>::element_type*>()(nullptr, rhs.get())
14) nullptr < lhs
15) rhs < nullptr
16) !(nullptr < lhs)
17) !(rhs < nullptr)
18) !(lhs < nullptr)
19) !(nullptr < rhs)
20) std::compare_three_way{}(x.get(), static_cast<std::shared_ptr<T>::element_type*>(nullptr))

Примечания

Во всех случаях сравнивается сохранённый указатель (возвращаемый get()), а не управляемый указатель (передаваемый деструктору, когда use_count становится нулевым). Два указателя могут отличаться в случае shared_ptr созданного с помощью конструктора алиасов.

Пример

#include <iostream>
#include <memory>
 
int main()
{
    std::shared_ptr<int> p1(new int(42));
    std::shared_ptr<int> p2(new int(42));
 
    std::cout << std::boolalpha
        << "(p1 == p1)       : " << (p1 == p1) << '\n'
        << "(p1 <=> p1) == 0 : " << ((p1 <=> p1) == 0) << '\n' // Since C++20
 
    // p1 and p2 point to different memory locations, so p1 != p2
        << "(p1 == p2)       : " << (p1 == p2) << '\n'
        << "(p1 < p2)        : " << (p1 < p2) << '\n'
        << "(p1 <=> p2) < 0  : " << ((p1 <=> p2) < 0) << '\n'   // Since C++20
        << "(p1 <=> p2) == 0 : " << ((p1 <=> p2) == 0) << '\n'; // Since C++20
}

Возможный вывод:

(p1 == p1)       : true
(p1 <=> p1) == 0 : true
(p1 == p2)       : false
(p1 < p2)        : true
(p1 <=> p2) < 0  : true
(p1 <=> p2) == 0 : false

Отчеты об ошибках

Следующие отчеты об ошибках, изменяющие поведение, были применены ретроактивно к ранее опубликованным стандартам C++.

DR Применён к Поведение, как опубликовано Правильное поведение
LWG 3427 C++20 operator<=>(shared_ptr, nullptr_t) было некорректным определение исправлено

См. также

get
возвращает сохранённый указатель
(публичный член-функция)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmp

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API