Returning unique_ptr Ownership

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

// This function is responsible for creating the buffer
// and returning ownership to the caller.
unique_ptr<uint8_t[]> createBuffer(int n) {
    // Allocate a buffer of size n
    unique_ptr<uint8_t[]> buf(new uint8_t[n]);

    for (int i = 0; i < n; i++) {
        int temp;
        cin >> temp;
        // Store input into the buffer
        buf[i] = static_cast<uint8_t>(temp);
    }

    // Return ownership of the buffer
    return buf; 
}

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

    // Receive ownership from the function
    unique_ptr<uint8_t[]> buffer = createBuffer(N);

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

    return 0;
}

Solving Approach

 

 

 


 

Upvote
Downvote
Loading...

Input

1 0

Expected Output

0