Example of weak_ptr
The following example demonstrates how the weak_ptr solves the circular reference problem.
C++
// C++ program to illustrate the use of weak_ptr #include <iostream> #include <memory> using namespace std; // declaring a dummy object class Object { public : Object( int value) : data(value) { cout << "Object created with value: " << data << endl; } ~Object() { cout << "Object destroyed with value: " << data << endl; } int data; }; // driver code int main() { // creating shared pointer with resource ownership shared_ptr<Object> sharedObjectA = make_shared<Object>(42); // creating weak pointer to the previously created // shared objects weak_ptr<Object> weakObjectA = sharedObjectA; // Access objects using weak_ptr if (!weakObjectA.expired()) { cout << "The value stored in sharedObjectA:" << (*weakObjectA.lock()).data << endl; } // deleting object sharedObjectA.reset(); cout << "End of the Program" ; return 0; } |
Output
Object created with value: 42 The value stored in sharedObjectA:42 Object destroyed with value: 42 End of the Program
In this example, we create a shared_ptr with the ownership of a dynamically created object. Then we created a weak_ptr which refers to the same resource as that of shared_ptr. After resetting the shared_ptr, we can see that its is destroyed and deallocated from the memory.
weak_ptr in C++
The weak_ptr is one of the smart pointers that provide the capability of a pointer with some reduced risks as compared to the raw pointer. The weak_ptr, just like shared_ptr has the capability to point to the resource owned by another shared_ptr but without owning it. In other words, they are able to create a non-owning reference to the object managed by shared_ptr.
Contact Us