Namespaces
Variants

std::weak_ptr<T>:: lock

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)
std:: shared_ptr < T > lock ( ) const noexcept ;
(C++11부터)

관리 중인 객체의 소유권을 공유하는 새로운 std::shared_ptr 을 생성합니다. 관리 중인 객체가 없는 경우, 즉 * this 가 비어 있는 경우, 반환된 shared_ptr 또한 비어 있습니다.

효과적으로 expired ( ) ? shared_ptr < T > ( ) : shared_ptr < T > ( * this ) 를 반환하며, 원자적으로 실행됩니다.

목차

반환값

소유된 객체에 대한 소유권을 공유하는 shared_ptr 을 반환합니다. 단, std::weak_ptr::expired false 를 반환하는 경우에 한합니다. 그렇지 않으면 기본 생성된 shared_ptr T 타입으로 반환합니다.

참고 사항

이 함수와 std::shared_ptr 의 생성자 모두 std::weak_ptr 이 참조하는 관리 객체에 대한 임시 소유권을 획득하는 데 사용될 수 있습니다. 차이점은 std::shared_ptr 의 생성자는 인자로 전달된 std::weak_ptr 이 비어 있을 때 예외를 발생시키는 반면, std::weak_ptr<T>::lock() 은 빈 std::shared_ptr<T> 을 생성한다는 점입니다.

예제

#include <iostream>
#include <memory>
void observe(std::weak_ptr<int> weak)
{
    if (auto p = weak.lock())
        std::cout << "\tobserve() is able to lock weak_ptr<>, value=" << *p << '\n';
    else
        std::cout << "\tobserve() is unable to lock weak_ptr<>\n";
}
int main()
{
    std::weak_ptr<int> weak;
    std::cout << "weak_ptr<> is not yet initialized\n";
    observe(weak);
    {
        auto shared = std::make_shared<int>(42);
        weak = shared;
        std::cout << "weak_ptr<> is initialized with shared_ptr\n";
        observe(weak);
    }
    std::cout << "shared_ptr<> has been destructed due to scope exit\n";
    observe(weak);
}

출력:

weak_ptr<> is not yet initialized
        observe() is unable to lock weak_ptr<>
weak_ptr<> is initialized with shared_ptr
        observe() is able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit
        observe() is unable to lock weak_ptr<>

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2316 C++11 lock()이 atomic일 것을 요구하지 않았으나 noexcept를 요구하여 모순이 발생함 atomic으로 명시됨

참고 항목

참조된 객체가 이미 삭제되었는지 확인합니다
(public member function)