59. unique_ptr RAII Basics

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

int main() {
    int N;
    cin >> N;

    {
        // unique_ptr owns the buffer within this scope
        unique_ptr<int[]> data(new int[N]);

        for (int i = 0; i < N; i++) {
            cin >> data[i];
        }

        for (int i = 0; i < N; i++) {
            cout << data[i];
            if (i != N - 1) cout << " ";
        }
        cout << endl;
    }

    cout << "Scope ended" << endl;
    return 0;
}

Explanation & Logic Summary:

The buffer is owned by a std::unique_ptr declared inside a local scope. When execution leaves that scope, the unique_ptr is destroyed automatically, and its destructor releases the memory it owns. No explicit cleanup code is required. This demonstrates RAII: resource management is bound to object lifetime.

Firmware Relevance & Real-World Context:

In firmware and embedded systems, resources such as memory buffers are often allocated for a limited duration. Using RAII ensures deterministic cleanup when execution exits a scope, simplifying control flow and preventing leaks in long-running or safety-critical systems.

 

 

 

 

Loading...

Input

1 0

Expected Output

0 Scope ended