example3_monitor_expensive_resource.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <memory>
#include <iostream>
using namespace std;

class LargeResource
{
public:
    LargeResource() { std::cout << "LargeResource Acquired" << std::endl; }
    ~LargeResource() { std::cout << "LargeResource Released" << std::endl; }
    void useResource() const { std::cout << "Using LargeResource" << std::endl; }
};

std::weak_ptr<LargeResource> globalWeakPtr;

void monitorResource()
{
    if (std::shared_ptr<LargeResource> resPtr = globalWeakPtr.lock())
    {
        resPtr->useResource();
    }
    else
    {
        std::cout << "Resource is no longer available" << std::endl;
    }
}

int main()
{
    {
        std::shared_ptr<LargeResource> resPtr = std::make_shared<LargeResource>();
        globalWeakPtr = resPtr; // Create a weak reference to the resource

        monitorResource(); // Resource is available
        cout << "resPtr count: " << resPtr.use_count() << endl;

        // When exiting local context {}, the count is decreased by 1. Once the count
        // reaches 0, the resource is released
    }
    // Resource is released
    cout << "after closing  }, resource released before this point" << endl;

    // After resPtr goes out of scope, the resource is released

    cout << "before 2nd monitor" << endl;
    monitorResource(); // Resource is no longer available

    return 0;
}
Back to std_weak_ptr