#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;
}