example1_basic.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
#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;
}
Back to std_weak_ptr