이이프 2022. 10. 3. 09:32
728x90

1. weak_ptr

weak_ptr은 shared_ptr이 가리키는 리소스의 레퍼런스를 관리하는데 사용한다.

weak_ptr은 리소스를 직접 소유하지 않기 때문에 shared_ptr이 해당 리소스를 해제하는 데 아무런 영향을 미치지 않는다.

 

weak_ptr은 삭제될 때(예를 들어 스코프를 벗어날 때) 가리키던 리소스를 삭제하지 않고,

shared_ptr이 그 리소스를 해제했는지 알아낼 수 있다.

 

weak_ptr의 생성자는 shared_ptr이나 다른 weak_ptr을 인수로 받는다.

weak_ptr에 저장된 포인터에 접근하려면 shared_ptr로 변환해야 한다.

 

weak_ptr을 사용하는 예는 다음과 같다.

#include <iostream>
using namespace std;

class Simple
{
public:
    Simple() { cout << "Simple constructor called!" << endl; }
    ~Simple() { cout << "Simple destructor called!" << endl; }
};

void useResource(weak_ptr<Simple>& weakSimple)
{
    auto resource = weakSimple.lock();
    if (resource) {
        cout << "Resource still alive." << endl;
    }
    else {
        cout << "Resource has been freed" << endl;
    }
}

int main()
{
    auto sharedSimple = make_shared<Simple>();
    weak_ptr<Simple> weakSimple(sharedSimple);

    // weak_ptr을 사용한다.
    useResource(weakSimple);

    // shared_ptr을 리셋한다.
    // Simple 리소스에 대한 shared_ptr은 하나뿐이므로
    // weak_ptr이 살아 있더라도 리소스가 해제된다.
    sharedSimple.reset();

    // weak_ptr을 한 번 더 사용한다.
    useResource(weakSimple);

    return 0;
}

실행 결과

weak_ptr 인스턴스의 lock() 메서드를 이용하여 shared_ptr을 리턴받는다.

이때 shared_ptr에 연결된 weak_ptr이 해제되면 shared_ptr의 값은 nullptr이 된다.