unique_ptr RAII Basics

#include <iostream>
#include <memory>

using namespace std;

int main() {
    int N;
    if (!(cin >> N)) return 0;

    {
        // 1. Declare and allocate a unique_ptr to manage a dynamic integer array of size N
        // make_unique is the modern, exception-safe way to initialize smart pointers.
        std::unique_ptr<int[]> buffer = std::make_unique<int[]>(N);

        for (int i = 0; i < N; i++) {
            int temp;
            cin >> temp;
            // 2. Store value in the buffer using array indexing
            buffer[i] = temp;
        }

        for (int i = 0; i < N; i++) {
            // 3. Print buffer values
            cout << buffer[i];
            if (i != N - 1) cout << " ";
        }
        cout << endl;
        
        // As we reach this brace, 'buffer' goes out of scope and memory is freed automatically.
    }

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

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1 0

Expected Output

0 Scope ended