Returning unique_ptr Ownership

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

// Function creates and initializes the buffer,
// then transfers ownership to the caller.
unique_ptr<uint8_t[]> createBuffer(int n) {
    unique_ptr<uint8_t[]> buf(new uint8_t[n]);

    for (int i = 0; i < n; i++) {
        int temp;
        cin >> temp;
        buf[i] = static_cast<uint8_t>(temp);
    }

    // Ownership moves to the caller via return value
    return buf;
}

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

    // main now owns the buffer
    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