shared_ptr_operator_cmp

shared_ptr_operator_cmp (shared_ptr 비교 연산자)

<memory> 헤더에 정의되어 있어요. 두 std::shared_ptr 객체 또는 std::shared_ptr과 널 포인터를 비교해요. C++11부터 도입됐어요.

출처: cppreference

본문

shared_ptr 객체 비교:

template< class T, class U >
bool operator==( const std::shared_ptr<T>& lhs, const std::shared_ptr<U>& rhs ) noexcept;   // (1)
template< class T, class U >
std::strong_ordering operator<=>( const std::shared_ptr<T>& lhs, const std::shared_ptr<U>& rhs ) noexcept;  // (7) since C++20

shared_ptr과 널 포인터 비교:

template< class T >
bool operator==( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;  // (8)
template< class T >
std::strong_ordering operator<=>( const std::shared_ptr<T>& lhs, std::nullptr_t ) noexcept;  // (20) since C++20

(1,3-6,8-19는 C++11, C++20에서 <=>/==로 합성됨)

shared_ptr<T> 객체 또는 shared_ptr<T>와 널 포인터를 비교해요. 비교 연산자는 단순히 포인터 값을 비교하며, 가리키는 실제 객체는 비교하지 않아요. shared_ptr에 대해 operator<가 정의되어 있어 std::map·std::set 같은 연관 컨테이너의 키로 쓸 수 있어요.

<, <=, >, >=, != 연산자는 <=>==로부터 합성돼요. (C++20)

반환값

  • (1) lhs.get() == rhs.get()
  • (7) std::compare_three_way{}(x.get(), y.get())
  • (8) !lhs (즉 lhs가 널이면 true)

주의 (Notes)

모든 경우에 비교되는 것은 저장된 포인터(get()이 돌려주는 것)이지, 관리되는 포인터(use_count가 0이 될 때 삭제자에 전달되는 것)가 아니에요. aliasing 생성자로 만든 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 == p2)       : " << (p1 == p2) << '\n'   // 서로 다른 주소
        << "(p1 < p2)        : " << (p1 < p2) << '\n';
}

결함 보고 (Defect reports)

LWG 3427은 C++20에서 operator<=>(shared_ptr, nullptr_t)가 ill-formed이던 것을 정의를 고쳤어요.

더 알아보기 (Learn more)

cppreference