#include <iostream>
#include <memory>
using namespace std;
class Sensor {
public:
int read() { return 42; }
};
int main() {
unique_ptr<Sensor> s = make_unique<Sensor>();
cout << "Sensor reading: " << s->read();
return 0;
}
Solution Explanation
unique_ptr<Sensor>
owns the Sensor object exclusively.make_unique<Sensor>()
creates the object safely.s->read()
calls the function on the managed object.delete
; memory
is released automatically.Layman’s Terms
It’s like borrowing a tool and putting it back automatically when you’re done — you don’t have to remember to return it manually.
Significance for Embedded Developers
Even though dynamic memory is limited in embedded systems, unique_ptr is useful in:
Input
Expected Output
Sensor reading: 42