#include <iostream>
#include <cstdint>
using namespace std;
class Buffer {
private:
uint8_t* data;
int size;
public:
Buffer(int n) : data(nullptr), size(n) {
data = new uint8_t[size];
}
// Disable copy assignment to enforce exclusive ownership
Buffer& operator=(const Buffer&) = delete;
// Move assignment operator
Buffer& operator=(Buffer&& other) noexcept {
if (this == &other) {
return *this;
}
// Release current resource
delete[] data;
// Transfer ownership
data = other.data;
size = other.size;
// Reset source object
other.data = nullptr;
other.size = 0;
return *this;
}
~Buffer() {
delete[] data;
}
void set(int index, uint8_t value) {
data[index] = value;
}
void print() const {
if (data == nullptr || size == 0) {
cout << "No data";
} else {
for (int i = 0; i < size; i++) {
cout << (int)data[i];
if (i != size - 1) cout << " ";
}
}
cout << endl;
}
};
int main() {
int N, M;
cin >> N;
Buffer A(N);
for (int i = 0; i < N; i++) {
int temp;
cin >> temp;
A.set(i, (uint8_t)temp);
}
cin >> M;
Buffer B(M);
for (int i = 0; i < M; i++) {
int temp;
cin >> temp;
B.set(i, (uint8_t)temp);
}
A = std::move(B); // Correct: ownership transfer
A.print();
B.print();
return 0;
}
Explanation & Logic Summary:
This problem enforces exclusive ownership of a dynamically allocated buffer.
Allowing copy assignment would duplicate ownership, leading to double frees or an inconsistent system state.
By deleting the copy assignment operator and implementing a move assignment operator:
This follows the Rule of Five principles and reflects best practices for resource-managing classes in Embedded C++.
Firmware Relevance & Real-World Context:
In firmware and embedded systems, buffers often represent:
Move semantics allow zero-copy ownership transfer, improving performance and preventing critical resource duplication bugs—making this a highly relevant real-world Embedded C++ exercise.
Input
4 10 20 30 40 3 1 2 3
Expected Output
1 2 3 No data