unique_ptr Ownership Consume

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

// This function is intended to take ownership,
// but its signature does not express that clearly.
void consumeBuffer(unique_ptr<uint8_t[]> buf, int size) {
    for (int i = 0; i < size; i++) {
        cout << static_cast<int>(buf[i]);
        if (i != size - 1) cout << " ";
    }
    cout << endl;
}

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

    unique_ptr<uint8_t[]> buffer(new uint8_t[N]);

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

    // Transfer ownership to the function
    consumeBuffer(std::move(buffer), N);

    if (buffer == nullptr)
        cout << "No data" << endl;
    else
        cout << "Has data" << endl;

    return 0;
}
Upvote
Downvote
Loading...

Input

4 10 20 30 40

Expected Output

10 20 30 40 No data