45. Manage a Device with a unique_ptr

#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.
  • No need for 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:

  • Test harnesses (mocking devices).
  • Higher-level embedded applications where dynamic allocation is unavoidable.
  • Guaranteeing no memory leaks when managing peripheral drivers or buffers.
Loading...

Input

Expected Output

Sensor reading: 42