#include <iostream>
#include <cstdint>
#include <memory>
using namespace std;
/**
* Creates a dynamic buffer and returns exclusive ownership.
* @param n The size of the buffer to allocate.
* @return A unique_ptr managing the allocated uint8_t array.
*/
unique_ptr<uint8_t[]> createBuffer(int n) {
// 1. Allocate a buffer of size n using make_unique for exception safety
auto buffer = make_unique<uint8_t[]>(n);
for (int i = 0; i < n; i++) {
int temp;
if (cin >> temp) {
// 2. Store input into the buffer (casting to uint8_t)
buffer[i] = static_cast<uint8_t>(temp);
}
}
// 3. Return ownership of the buffer to the caller
// The move happens automatically due to Return Value Optimization (RVO)
return buffer;
}
int main() {
int N;
if (!(cin >> N)) return 0;
// Receive ownership from the function
// The 'buffer' in main now solely owns the memory created in createBuffer
unique_ptr<uint8_t[]> buffer = createBuffer(N);
// Print the buffer contents
for (int i = 0; i < N; i++) {
// Cast to int for printing, otherwise uint8_t might be treated as a char
cout << static_cast<int>(buffer[i]);
if (i != N - 1) cout << " ";
}
cout << endl;
// No manual delete needed! Memory is freed here automatically.
return 0;
}
Input
1 0
Expected Output
0