#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.shared_ptr
that manage the same object.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:
Input
Expected Output
Logging data Logging data