Namespaces
Variants

std::weak_ptr<T>:: owner_before

From cppreference.net

Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
template < class Y >
bool owner_before ( const weak_ptr < Y > & other ) const noexcept ;
template < class Y >
bool owner_before ( const std:: shared_ptr < Y > & other ) const noexcept ;

weak_ptr 가 구현에서 정의된 소유자 기반 (값 기반이 아닌) 순서에서 other 보다 앞서는지 확인합니다. 이 순서는 두 스마트 포인터가 모두 비어 있거나 동일한 객체를 소유하는 경우에만 동등하게 비교되며, get() 로 얻은 포인터 값이 다르더라도 (예: 동일한 객체 내의 다른 하위 객체를 가리키는 경우) 마찬가지입니다.

이 순서 지정은 공유 포인터와 약한 포인터를 연관 컨테이너의 키로 사용할 수 있게 하기 위해 사용되며, 일반적으로 std::owner_less 를 통해 구현됩니다.

목차

매개변수

other - 비교할 std::shared_ptr 또는 std::weak_ptr

반환값

true 만약 * this other 보다 앞서는 경우, 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++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2083 C++11 owner_before const 로 선언되지 않음 const 로 선언됨
LWG 2942 C++11 owner_before noexcept 로 선언되지 않음 noexcept 로 선언됨

참고 항목

(C++11)
shared 및 weak 포인터의 혼합 타입 소유자 기반 순서 지정을 제공함
(클래스 템플릿)