46. Access Object with shared_ptr

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

class Logger {
public:
    void log() { cout << "Logging data\n"; }
};

int main() {
    shared_ptr<Logger> p1 = make_shared<Logger>();
    shared_ptr<Logger> p2 = p1; // shared ownership

    p1->log();
    p2->log();

    return 0;
}

 

Solution Explanation

  • make_shared<Logger>() creates a Logger object on the heap.
  • p1 and p2 are both shared_ptr that manage the same object.
  • The reference count ensures the object is deleted only when all owners are gone.

     

Layman’s Terms

Think of it like two friends sharing the same house key. They can both use the house (log()), and the house is cleaned up only when both give up their keys.

 

Significance for Embedded Developers

While shared_ptr is less common in tight bare-metal systems (due to overhead), it’s useful in:

  • RTOS or embedded Linux applications where multiple modules need safe access to a shared resource (like a logger, configuration, or buffer).
  • Avoiding manual reference counting bugs.

     
Loading...

Input

Expected Output

Logging data Logging data