#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass Constructor" << std::endl; }
~MyClass() { std::cout << "MyClass Destructor" << std::endl; }
void sayHello() const { std::cout << "Hello from MyClass" << std::endl; }
};
int main() {
std::shared_ptr<MyClass> sharedPtr = std::make_shared<MyClass>();
std::weak_ptr<MyClass> weakPtr = sharedPtr; // Create a weak_ptr from shared_ptr
if (std::shared_ptr<MyClass> lockedPtr = weakPtr.lock()) {
// Successfully locked the weak_ptr, object is still alive
lockedPtr->sayHello();
} else {
std::cout << "Object has been destroyed" << std::endl;
}
sharedPtr.reset(); // Manually release the shared ownership
if (std::shared_ptr<MyClass> lockedPtr = weakPtr.lock()) {
std::cout << "Object is still alive" << std::endl;
} else {
std::cout << "Object has been destroyed" << std::endl;
}
return 0;
}