unique_ptr Ownership Consume

#include <iostream>
#include <cstdint>
#include <memory>

using namespace std;

/**
 * @brief Consumes the buffer by taking full ownership.
 * @param ptr The unique_ptr being moved into the function.
 * @param size The number of elements in the buffer.
 */
void consumeBuffer(unique_ptr<uint8_t[]> ptr, int size) {
    // Ownership has been transferred to 'ptr'.
    // Once this function scope ends, 'ptr' will delete the memory.
    for (int i = 0; i < size; i++) {
        // We cast to int to ensure uint8_t prints as a number, not a char
        cout << (int)ptr[i];
        if (i != size - 1) {
            cout << " ";
        }
    }
    cout << endl;
}

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

    // Create a unique_ptr that owns a buffer of N bytes
    unique_ptr<uint8_t[]> buffer(new uint8_t[N]);

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

    // Explicit ownership transfer using std::move.
    // The signature of consumeBuffer forces this explicit intent.
    consumeBuffer(std::move(buffer), N);

    // After the call, the caller must have no ownership
    if (buffer == nullptr)
        cout << "No data" << endl;
    else
        cout << "Has data" << endl;

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

4 10 20 30 40

Expected Output

10 20 30 40 No data