47. Access Object with weak_ptr

#include <iostream>
#include <memory>
using namespace std;

class Device {
public:
    void status() { cout << "Device is active\n"; }
};

int main() {
    shared_ptr<Device> sp = make_shared<Device>();
    weak_ptr<Device> wp = sp; // observes sp

    if (auto temp = wp.lock()) {
        temp->status();
    }
    return 0;
}

 

Solution Explanation

  • shared_ptr<Device> sp = make_shared<Device>(); creates and owns the Device.
  • weak_ptr<Device> wp = sp; observes the same object but does not increase its reference count.
  • The given if (auto temp = wp.lock()) safely accesses the object if it’s still alive.
     

Layman’s Terms

A shared_ptr is like holding the real house key. A weak_ptr is like a visitor’s pass — it doesn’t own the house but can step inside if the real owner still exists.

 

Significance for Embedded Developers

  • Useful for observer patterns where multiple components monitor a device but don’t own it.
  • Helps prevent circular references in firmware modules.

     
Loading...

Input

Expected Output

Device is active