Move Constructor Buffer Transfer

#include <iostream>
#include <cstdint>
#include <utility> // Required for std::move

using namespace std;

class SensorBuffer {
private:
    uint8_t* data;
    int size;

public:
    // Standard Constructor
    SensorBuffer(int n) : data(new uint8_t[n]), size(n) {}

    // --- Move Constructor ---
    // Takes an rvalue reference (&&) to the source object 'other'
    SensorBuffer(SensorBuffer&& other) noexcept : data(other.data), size(other.size) {
        // 1. Transfer ownership: our 'data' now points to other's memory.
        // 2. Leave the source in a valid, empty state:
        other.data = nullptr;
        other.size = 0;
    }

    // Destructor
    ~SensorBuffer() {
        // Deleting a nullptr is safe in C++, so no extra check is needed here,
        // but it will only free memory if 'data' is still valid.
        delete[] data;
    }

    // Prevent copying to ensure we only use move semantics for this exercise
    SensorBuffer(const SensorBuffer&) = delete;
    SensorBuffer& operator=(const SensorBuffer&) = delete;

    void set(int index, uint8_t value) {
        if (data) {
            data[index] = value;
        }
    }

    void print() const {
        // Check if the buffer is empty or nullified after a move
        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;
    if (!(cin >> N)) return 0;

    SensorBuffer A(N);
    for (int i = 0; i < N; i++) {
        int temp;
        cin >> temp;
        A.set(i, static_cast<uint8_t>(temp));
    }

    // Move construction: B takes ownership of A's resources
    SensorBuffer B = std::move(A);

    A.print(); // Should print "No data"
    B.print(); // Should print the original bytes

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1 42

Expected Output

No data 42